<?php
// Secure token check to prevent unauthorized execution
if (($_GET['token'] ?? '') !== 'nabeh_test_audio_1298') {
    http_response_code(403);
    die('Unauthorized access');
}

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Core\Database;

header('Content-Type: text/plain; charset=utf-8');

echo "=== Gemini Available Models Diagnostics ===\n\n";

$rules = Database::select("SELECT * FROM chatbot_rules WHERE trigger_type = 'gemini_ai' AND is_active = 1 LIMIT 1");
if (empty($rules)) {
    echo "❌ [Database] No active chatbot rule found.\n";
    exit(1);
}

$rule = $rules[0];
$apiKey = $rule['gemini_api_key'] ?: getenv('GEMINI_API_KEY');

if (empty($apiKey)) {
    echo "❌ [Config] Gemini API Key is empty.\n";
    exit(1);
}

$url = 'https://generativelanguage.googleapis.com/v1beta/models?key=' . $apiKey;

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200) {
    echo "❌ [Gemini API Error] HTTP Status: " . $httpCode . "\n";
    echo "Response: " . $response . "\n";
    exit(1);
}

$data = json_decode($response, true);
if (empty($data['models'])) {
    echo "❌ [Gemini] No models returned or invalid response structure.\n";
    echo "Response: " . print_r($data, true) . "\n";
    exit(1);
}

echo "Found " . count($data['models']) . " models:\n\n";
foreach ($data['models'] as $model) {
    echo "Model Name: " . $model['name'] . "\n";
    echo "Display Name: " . $model['displayName'] . "\n";
    echo "Supported Methods: " . implode(', ', $model['supportedGenerationMethods'] ?? []) . "\n";
    if (isset($model['inputTokenLimit'])) {
        echo "Input Token Limit: " . $model['inputTokenLimit'] . "\n";
    }
    if (isset($model['outputTokenLimit'])) {
        echo "Output Token Limit: " . $model['outputTokenLimit'] . "\n";
    }
    echo "----------------------------------------\n";
}
