<?php
/**
 * AI Writer API
 * Generates content using AI writing service (External, Ollama, or OpenAI)
 */

require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Method not allowed', 405);
}

// Check authentication
if (!Auth::check()) {
    Response::error('Unauthorized', 401);
}

try {
    $input = json_decode(file_get_contents('php://input'), true);

    // Get AI settings
    $db = Database::getInstance()->getConnection();
    $stmt = $db->prepare("SELECT `key`, value_encrypted FROM settings WHERE section = 'ai'");
    $stmt->execute();
    $settings = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $key = strtoupper(str_replace('AI_', '', $row['key']));
        $settings[$key] = $row['value_encrypted'];
    }

    $serviceType = $settings['SERVICE_TYPE'] ?? 'ollama';

    // Prepare request data
    $topic = $input['topic'] ?? $settings['DEFAULT_TOPIC'] ?? 'general';
    $locale = $input['locale'] ?? $settings['DEFAULT_LOCALE'] ?? 'zh-TW';
    $length = $input['length'] ?? $settings['DEFAULT_LENGTH'] ?? 'short';
    $style = $input['style'] ?? 'casual';
    $keywords = $input['keywords'] ?? [];

    $result = null;
    $errors = [];

    // Try services in order: external -> ollama -> openai
    $services = ['external', 'ollama', 'openai'];
    if ($serviceType !== 'external') {
        // Prioritize selected service
        $services = array_unique([$serviceType, 'ollama', 'openai', 'external']);
    }

    foreach ($services as $service) {
        try {
            if ($service === 'external') {
                $result = generateWithExternal($settings, $topic, $locale, $length, $style, $keywords);
            } elseif ($service === 'ollama') {
                $result = generateWithOllama($settings, $topic, $locale, $length, $style, $keywords);
            } elseif ($service === 'openai') {
                $result = generateWithOpenAI($settings, $topic, $locale, $length, $style, $keywords);
            }

            if ($result) {
                break;
            }
        } catch (Exception $e) {
            $errors[$service] = $e->getMessage();
            continue;
        }
    }

    if (!$result) {
        $errorMsg = 'All AI services failed. Errors: ' . json_encode($errors);
        Response::error($errorMsg);
    }

    // Return generated content
    Response::success($result);

} catch (Exception $e) {
    Response::error('AI writer error: ' . $e->getMessage());
}

function generateWithExternal($settings, $topic, $locale, $length, $style, $keywords) {
    $baseUrl = $settings['BASE_URL'] ?? '';
    $apiKey = $settings['API_KEY'] ?? '';

    if (empty($baseUrl) || empty($apiKey)) {
        throw new Exception('External AI not configured');
    }

    $requestData = [
        'topic' => $topic,
        'locale' => $locale,
        'length' => $length,
        'need_media' => true,
        'style' => $style,
        'keywords' => $keywords
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, rtrim($baseUrl, '/') . '/api/generate');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

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

    if ($error || $httpCode !== 200) {
        throw new Exception('External service failed');
    }

    $result = json_decode($response, true);
    if (!$result || !isset($result['content'])) {
        throw new Exception('Invalid response from external service');
    }

    return [
        'content' => $result['content'],
        'title' => $result['title'] ?? '',
        'hashtags' => $result['hashtags'] ?? [],
        'media_suggestions' => $result['media_suggestions'] ?? []
    ];
}

function generateWithOllama($settings, $topic, $locale, $length, $style, $keywords) {
    $baseUrl = $settings['OLLAMA_BASE_URL'] ?? '';
    $model = $settings['OLLAMA_MODEL'] ?? 'gemma2:2b';

    if (empty($baseUrl)) {
        throw new Exception('Ollama not configured');
    }

    $lengthMap = [
        'short' => '200-300字',
        'medium' => '400-600字',
        'long' => '800-1200字'
    ];
    $lengthDesc = $lengthMap[$length] ?? '200-300字';

    $keywordsText = empty($keywords) ? '' : '關鍵詞：' . implode('、', $keywords) . "\n";

    $prompt = "請以{$style}風格用{$locale}撰寫一篇關於「{$topic}」的社交媒體貼文。\n{$keywordsText}長度：{$lengthDesc}\n\n請用JSON格式回答，包含以下欄位：\n{\"title\": \"標題\", \"content\": \"內容\", \"hashtags\": [\"標籤1\", \"標籤2\"]}";

    $requestData = [
        'model' => $model,
        'prompt' => $prompt,
        'stream' => false,
        'options' => [
            'temperature' => 0.7,
            'top_p' => 0.9
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, rtrim($baseUrl, '/') . '/api/generate');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);

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

    if ($error || $httpCode !== 200) {
        throw new Exception('Ollama service failed: ' . ($error ?: 'HTTP ' . $httpCode));
    }

    $result = json_decode($response, true);
    if (!$result || !isset($result['response'])) {
        throw new Exception('Invalid response from Ollama');
    }

    $aiResponse = $result['response'];

    // Try to parse JSON from response (handle nested braces)
    if (preg_match('/\{.*"content".*\}/s', $aiResponse, $matches)) {
        $parsed = json_decode($matches[0], true);
        if ($parsed && isset($parsed['content'])) {
            return [
                'content' => $parsed['content'],
                'title' => $parsed['title'] ?? $topic,
                'hashtags' => $parsed['hashtags'] ?? $keywords,
                'media_suggestions' => []
            ];
        }
    }

    // Fallback: use raw response as content
    return [
        'content' => $aiResponse,
        'title' => $topic,
        'hashtags' => $keywords,
        'media_suggestions' => []
    ];
}

function generateWithOpenAI($settings, $topic, $locale, $length, $style, $keywords) {
    $apiKey = $settings['OPENAI_API_KEY'] ?? '';
    $model = $settings['OPENAI_MODEL'] ?? 'gpt-4o-mini';

    if (empty($apiKey)) {
        throw new Exception('OpenAI not configured');
    }

    $lengthMap = [
        'short' => '200-300字',
        'medium' => '400-600字',
        'long' => '800-1200字'
    ];
    $lengthDesc = $lengthMap[$length] ?? '200-300字';

    $keywordsText = empty($keywords) ? '' : '關鍵詞：' . implode('、', $keywords) . "\n";

    $prompt = "請以{$style}風格用{$locale}撰寫一篇關於「{$topic}」的社交媒體貼文。\n{$keywordsText}長度：{$lengthDesc}\n\n請用JSON格式回答，包含以下欄位：\n{\"title\": \"標題\", \"content\": \"內容\", \"hashtags\": [\"標籤1\", \"標籤2\"]}";

    $requestData = [
        'model' => $model,
        'messages' => [
            ['role' => 'system', 'content' => 'You are a professional social media content writer.'],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.7
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

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

    if ($error || $httpCode !== 200) {
        throw new Exception('OpenAI service failed');
    }

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

    $content = $result['choices'][0]['message']['content'];

    // Try to parse JSON (handle nested braces)
    if (preg_match('/\{.*"content".*\}/s', $content, $matches)) {
        $parsed = json_decode($matches[0], true);
        if ($parsed && isset($parsed['content'])) {
            return [
                'content' => $parsed['content'],
                'title' => $parsed['title'] ?? $topic,
                'hashtags' => $parsed['hashtags'] ?? $keywords,
                'media_suggestions' => []
            ];
        }
    }

    return [
        'content' => $content,
        'title' => $topic,
        'hashtags' => $keywords,
        'media_suggestions' => []
    ];
}
