<?php
namespace Peak;

class VideoGenerator {
    public static function handleRequest(): void {
        $raw = file_get_contents('php://input');
        if (!$raw) Response::error('Empty request body', 400);
        $data = json_decode($raw, true);
        if (!$data) Response::error('Invalid JSON: ' . substr($raw, 0, 200), 400);
        $prompt = trim($data['prompt'] ?? '');
        $model = $data['model'] ?? 'google/gemini-2.5-flash-preview-image';
        if (!$prompt) Response::error('Prompt is required');

        if (strpos($model, 'google/') === 0) {
            self::generateViaGemini($prompt, $model);
        } else {
            Response::error('Unsupported model: ' . $model, 400);
        }
    }

    private static function resolveModel(string $model): string {
        $m = str_replace('google/', '', $model);
        $m = preg_replace('/-image$/', '', $m);
        $m = str_replace('-preview', '', $m);
        $map = [
            'gemini-2.5-flash-preview' => 'gemini-2.5-flash-preview-05-08',
            'gemini-2.0-flash-exp' => 'gemini-2.0-flash-exp-image-generation',
        ];
        return $map[$m] ?? $m;
    }

    private static function generateViaGemini(string $prompt, string $model): void {
        $googleModel = self::resolveModel($model);
        $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . $googleModel . ':generateContent?key=' . Config::$GEMINI_API_KEY;
        $body = json_encode([
            'contents' => [['parts' => [['text' => $prompt]]]],
            'generationConfig' => ['responseModalities' => ['Text', 'Image']]
        ]);
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        if ($response === false) Response::error('Gemini: connection error: ' . ($error ?: 'unknown'), 502);
        if ($httpCode < 200 || $httpCode >= 300) {
            $parsed = json_decode($response, true);
            $msg = $parsed['error']['message'] ?? $parsed['error'] ?? substr($response, 0, 500);
            Response::error('Gemini: ' . $msg, 502);
        }
        $parsed = json_decode($response, true);
        if (!$parsed) Response::error('Gemini: invalid response', 502);
        $images = [];
        foreach ($parsed['candidates'] ?? [] as $c) {
            foreach ($c['content']['parts'] ?? [] as $p) {
                if (!empty($p['inlineData']['data'])) {
                    $mime = $p['inlineData']['mimeType'];
                    $images[] = ['url' => 'data:' . $mime . ';base64,' . $p['inlineData']['data']];
                }
            }
        }
        if (!empty($images)) Response::json(['data' => $images]);
        $text = $parsed['candidates'][0]['content']['parts'][0]['text'] ?? '';
        if ($text) {
            $svg = preg_replace('/^.*?(<svg)/s', '$1', $text);
            $svg = preg_replace('/(<\/svg>).*$/s', '$1', $svg);
            if (strpos($svg, '<svg') !== false) {
                Response::json(['data' => [['url' => 'data:image/svg+xml;base64,' . base64_encode($svg)]]]);
            }
            Response::error('Gemini: no media in response: ' . mb_substr($text, 0, 200), 503);
        }
        Response::error('Gemini: no media generated', 503);
    }
}
