<?php
// public_html/OCR/gemini_ephemeral_token.php
declare(strict_types=1);

/****************************************************
 * CORS (MATCH YOUR OCR ENDPOINT)
 ****************************************************/
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

$allowed_origins = [
    'http://localhost:5173',
    'http://172.20.48.1:5173',
    'https://skizagroundsuite.com',
];

if ($origin && in_array($origin, $allowed_origins, true)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: https://skizagroundsuite.com");
}

header("Vary: Origin");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

/****************************************************
 * POST ONLY
 ****************************************************/
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Only POST allowed']);
    exit;
}

/****************************************************
 * SERVER API KEY (ENV → FALLBACK)
 ****************************************************/
$apiKey = getenv('GEMINI_API_KEY');
if (!$apiKey) {
    // temporary fallback (same approach as your gemini_client.php)
    $apiKey = 'AIzaSyDLXv9U1a7-4MJcA8fPlyL1987IVTGOQ2M';
}

if (!$apiKey) {
    http_response_code(500);
    echo json_encode([
        'status'  => 'error',
        'message' => 'GEMINI_API_KEY is not set and no fallback key is configured.',
    ]);
    exit;
}

/****************************************************
 * TOKEN CONFIG (MATCHES AuthToken schema)
 ****************************************************/
$expireTime = gmdate('c', time() + 30 * 60); // 30 minutes
$newSessionExpireTime = gmdate('c', time() + 60); // 60 seconds

// IMPORTANT:
// - Use camelCase for JSON field names on this endpoint:
//   expireTime, newSessionExpireTime, bidiGenerateContentSetup
// - Do NOT send http_options / live_connect_constraints here (endpoint rejects them).
$body = [
    'authToken' => [
        'uses' => 1,
        'expireTime' => $expireTime,
        'newSessionExpireTime' => $newSessionExpireTime,

        // Lock config using the supported union field:
        'bidiGenerateContentSetup' => [
            // model is part of the setup message
            'model' => 'gemini-2.5-flash-native-audio-preview-12-2025',

            // generationConfig is the correct place for responseModalities
            'generationConfig' => [
                'responseModalities' => ['AUDIO', 'TEXT'],
                // Optional tuning:
                // 'temperature' => 0.7,
            ],

            // Optional but useful:
            // 'systemInstruction' => 'You are a helpful assistant.',
        ],
    ],
];

$url = "https://generativelanguage.googleapis.com/v1alpha/auth_tokens?key=" . urlencode($apiKey);

/****************************************************
 * CURL REQUEST
 ****************************************************/
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($body),
    CURLOPT_TIMEOUT => 30,
]);

$response = curl_exec($ch);
$curlErrNo = curl_errno($ch);
$curlErr   = $curlErrNo ? curl_error($ch) : null;
$httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = null;
if (is_string($response) && $response !== '') {
    $data = json_decode($response, true);
}

// success typically includes data["name"] (token identifier)
if ($response === false || $httpCode !== 200 || empty($data['name'])) {
    http_response_code(502);
    echo json_encode([
        'status' => 'error',
        'message' => 'Token endpoint failed (upstream Google call).',
        'google_http_code' => $httpCode,
        'curl_errno' => $curlErrNo,
        'curl_error' => $curlErr,
        'google_json' => $data,
        'raw_response' => is_string($response) ? mb_substr($response, 0, 2000) : $response,
    ]);
    exit;
}

echo json_encode([
    'status' => 'ok',
    'token' => $data['name'],
    'expireTime' => $expireTime,
]);
