<?php

class OpenRouterHelper {
    private $apiKey;
    private $model;
    private $baseUrl = 'https://openrouter.ai/api/v1';

    public function __construct() {
        $this->apiKey = $_ENV['OPENROUTER_API_KEY'] ?? '';
        $this->model = $_ENV['OPENROUTER_MODEL'] ?? 'meta-llama/llama-3.1-8b-instruct:free';
    }

    /**
     * Check if OpenRouter is configured
     */
    public function isConfigured() {
        return !empty($this->apiKey);
    }

    /**
     * Get available models from OpenRouter
     */
    public function getModels() {
        if (!$this->isConfigured()) {
            return [];
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->baseUrl . '/models');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ]);

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

        if ($httpCode === 200) {
            $data = json_decode($response, true);
            return $data['data'] ?? [];
        }

        return [];
    }

    /**
     * Generate game description using OpenRouter AI
     */
    public function generateGameDescription($gameTitle, $gameCategory = null, $existingDescription = null) {
        if (!$this->isConfigured()) {
            throw new Exception('OpenRouter API key not configured');
        }

        $prompt = $this->buildPrompt($gameTitle, $gameCategory, $existingDescription);

        $data = [
            'model' => $this->model,
            'messages' => [
                [
                    'role' => 'user',
                    'content' => $prompt
                ]
            ],
            'max_tokens' => 300,
            'temperature' => 0.7
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->baseUrl . '/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json',
            'HTTP-Referer: ' . $_SERVER['HTTP_HOST'] ?? 'localhost',
            'X-Title: Game Portal AI Description Generator'
        ]);

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

        if ($error) {
            throw new Exception('cURL error: ' . $error);
        }

        if ($httpCode !== 200) {
            $errorData = json_decode($response, true);
            $errorMessage = $errorData['error']['message'] ?? 'Unknown error';
            throw new Exception('OpenRouter API error: ' . $errorMessage);
        }

        $responseData = json_decode($response, true);
        
        if (!isset($responseData['choices'][0]['message']['content'])) {
            throw new Exception('Invalid response from OpenRouter API');
        }

        return trim($responseData['choices'][0]['message']['content']);
    }

    /**
     * Build the prompt for game description generation
     */
    private function buildPrompt($gameTitle, $gameCategory = null, $existingDescription = null) {
        $categoryText = $gameCategory ? " in the {$gameCategory} category" : "";
        
        $basePrompt = "Write an engaging and concise description for a game called '{$gameTitle}'{$categoryText}.";
        
        // If there's an existing description, ask AI to improve it
        if (!empty($existingDescription)) {
            // Strip HTML tags for the prompt but mention HTML formatting is needed
            $cleanDescription = strip_tags($existingDescription);
            $basePrompt .= "\n\nCurrent description: \"{$cleanDescription}\"\n\nPlease improve and enhance this description, making it more engaging and appealing.";
        }
        
        $basePrompt .= "\n\nThe description should be:
- 2-3 sentences long
- Exciting and appealing to players
- Focused on gameplay and fun aspects
- Written in HTML format with basic tags like <p>, <strong>, <em> if needed
- Suitable for a game portal website

Do not include any introductory text, just provide the game description directly.";

        return $basePrompt;
    }

    /**
     * Get current API key
     */
    public function getApiKey() {
        return $this->apiKey;
    }

    /**
     * Get current model
     */
    public function getModel() {
        return $this->model;
    }
} 