<?php

/**
 * Phi-3 Mini Setup Script
 * This script helps you configure and test your Phi-3 Mini installation
 */

echo "🤖 Phi-3 Mini Setup Script\n";
echo "==========================\n\n";

// Check if Phi-3 Mini is running
function checkPhi3Connection($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return $httpCode === 200;
}

// Test different common Phi-3 Mini endpoints
$endpoints = [
    'http://localhost:8000/v1/chat/completions',
    'http://localhost:8000/chat/completions',
    'http://localhost:8000/api/v1/chat/completions',
    'http://localhost:8000/generate',
    'http://localhost:8000/',
];

echo "🔍 Checking Phi-3 Mini connection...\n";

$workingEndpoint = null;
foreach ($endpoints as $endpoint) {
    echo "Testing: $endpoint ... ";
    if (checkPhi3Connection($endpoint)) {
        echo "✅ Connected!\n";
        $workingEndpoint = $endpoint;
        break;
    } else {
        echo "❌ Failed\n";
    }
}

if (!$workingEndpoint) {
    echo "\n❌ Could not connect to Phi-3 Mini!\n";
    echo "\nPlease make sure:\n";
    echo "1. Phi-3 Mini is running\n";
    echo "2. It's accessible on localhost:8000\n";
    echo "3. The API endpoint is correct\n\n";
    
    echo "Common Phi-3 Mini startup commands:\n";
    echo "- ollama serve (if using Ollama)\n";
    echo "- python -m phi3_serve (if using direct Python)\n";
    echo "- docker run -p 8000:8000 phi3-mini (if using Docker)\n\n";
    
    exit(1);
}

echo "\n✅ Phi-3 Mini is running at: $workingEndpoint\n";

// Test a simple API call
echo "\n🧪 Testing API call...\n";

$testPayload = [
    'model' => 'phi3-mini',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Hello, are you working?'
        ]
    ],
    'max_tokens' => 50,
    'temperature' => 0.7
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $workingEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($testPayload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer phi3-mini-key'
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $data = json_decode($response, true);
    echo "✅ API call successful!\n";
    echo "Response: " . ($data['choices'][0]['message']['content'] ?? 'No content') . "\n";
} else {
    echo "❌ API call failed with HTTP $httpCode\n";
    echo "Response: $response\n";
}

// Generate .env configuration
echo "\n📝 Generating .env configuration...\n";

$envConfig = "\n# Phi-3 Mini Configuration\n";
$envConfig .= "PHI3_URL=$workingEndpoint\n";
$envConfig .= "PHI3_API_KEY=phi3-mini-key\n";
$envConfig .= "PHI3_MAX_TOKENS=1000\n";
$envConfig .= "PHI3_TEMPERATURE=0.7\n";
$envConfig .= "PHI3_TIMEOUT=30\n";
$envConfig .= "PHI3_MODEL_NAME=phi3-mini\n";

echo "Add this to your .env file:\n";
echo $envConfig;

// Save to .env file
$envFile = '.env';
if (file_exists($envFile)) {
    $currentEnv = file_get_contents($envFile);
    
    // Remove existing Phi-3 config
    $currentEnv = preg_replace('/# Phi-3 Mini Configuration.*?(?=\n[A-Z]|\Z)/s', '', $currentEnv);
    $currentEnv = preg_replace('/PHI3_.*?\n/', '', $currentEnv);
    
    // Add new config
    $currentEnv .= $envConfig;
    
    file_put_contents($envFile, $currentEnv);
    echo "\n✅ .env file updated!\n";
} else {
    echo "\n⚠️  .env file not found. Please add the configuration manually.\n";
}

echo "\n🎉 Setup complete!\n";
echo "You can now test the AI system at: http://your-domain/test-ai\n";
echo "Or access the AI dashboard at: http://your-domain/user/ai\n\n";

echo "Next steps:\n";
echo "1. Test the AI connection using the test page\n";
echo "2. Start a conversation in the AI dashboard\n";
echo "3. Customize the AI prompts for your use case\n";
echo "4. Add your own training data\n\n";
