<?php
/**
 * 根据页面标题调用 AI 模型生成 SEO 三件套（标题、关键词、描述）
 * 输入：POST { title }
 * 输出：JSON { ok, seo_title, seo_keywords, seo_description, model, error }
 */
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

@ini_set('display_errors', '0');
error_reporting(0);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

set_time_limit(60);
ob_start();

$title = isset($_POST['title']) ? trim((string)$_POST['title']) : '';
$domainId = isset($_POST['domain_id']) ? (int)$_POST['domain_id'] : 0;
$domain = $domainId > 0 ? find_domain_by_id($domainId) : null;
$siteLanguage = $domain ? domain_site_language($domain) : (isset($_POST['site_language']) ? trim((string)$_POST['site_language']) : '');
if ($siteLanguage === '') {
    $siteLanguage = 'auto';
}
$isEnglish = ($siteLanguage === 'en-US' || $siteLanguage === 'en-GB');

try {
    if ($title === '') {
        throw new Exception('请先填写页面标题再生成 SEO 信息。');
    }
    if (mb_strlen($title, 'UTF-8') > 200) {
        throw new Exception('标题过长（建议 <=200 字）。');
    }

    $model = null;
    $enabled = list_enabled_ai_model_options();
    if (empty($enabled)) {
        throw new Exception('尚未启用任何 AI 模型，请先在 AI 模型管理中配置并启用。');
    }
    $model = find_ai_model_by_id((int)$enabled[0]['id']);
    if (!$model) {
        throw new Exception('未找到可用的 AI 模型。');
    }

    $systemPrompt = $isEnglish
        ? 'You are a professional SEO expert. Given a page title, generate the following three fields in natural English: 1) seo_title — 50-80 characters, includes the core keyword and encourages clicks; 2) seo_keywords — 3-8 English keywords separated by commas; 3) seo_description — 120-160 characters, concise and keyword-rich. Return JSON only, no Markdown or extra explanation. If the title is Chinese, translate the meaning into English SEO terms instead of copying Chinese words. Example: {"seo_title":"...","seo_keywords":"...","seo_description":"..."}'
        : '你是一名中文 SEO 专家。用户会给你一个网页标题，请根据该标题生成以下三项内容：'
        . "\n1. seo_title — SEO 标题，50-80 字符，包含核心关键词，吸引点击"
        . "\n2. seo_keywords — SEO 关键词，3-8 个关键词，用英文逗号分隔"
        . "\n3. seo_description — SEO 描述，120-160 字符，简洁概括页面内容，包含核心关键词"
        . "\n\n严格以 JSON 格式返回，不要添加任何解释或 Markdown 代码块围栏。示例格式："
        . "\n{\"seo_title\":\"...\",\"seo_keywords\":\"...\",\"seo_description\":\"...\"}";
    $userPrompt = '页面标题：' . $title . "\n站点语言：" . $siteLanguage . "\n强制要求：如果站点语言是英文，所有内容必须是英文。";

    $messages = array(
        array('role' => 'system', 'content' => $systemPrompt),
        array('role' => 'user', 'content' => $userPrompt)
    );

    $aiResult = execute_ai_generation_request($model, $messages, false);
    $raw = isset($aiResult['assistant_text']) ? trim((string)$aiResult['assistant_text']) : '';

    // 清除可能夹带的 Markdown 代码块围栏
    if (preg_match('/```(?:json)?\s*([\s\S]*?)```/i', $raw, $matches)) {
        $raw = trim($matches[1]);
    }

    $parsed = json_decode($raw, true);
    if (!is_array($parsed)) {
        // 尝试从文本中提取 JSON 对象
        if (preg_match('/\{[^{}]*"seo_title"[^{}]*\}/s', $raw, $jsonMatch)) {
            $parsed = json_decode($jsonMatch[0], true);
        }
    }

    if (!is_array($parsed) || !isset($parsed['seo_title'])) {
        throw new Exception('AI 返回格式异常，请重试。原始返回：' . mb_substr($raw, 0, 200, 'UTF-8'));
    }

    ob_end_clean();
    echo json_encode(array(
        'ok' => true,
        'seo_title' => isset($parsed['seo_title']) ? trim((string)$parsed['seo_title']) : '',
        'seo_keywords' => isset($parsed['seo_keywords']) ? trim((string)$parsed['seo_keywords']) : '',
        'seo_description' => isset($parsed['seo_description']) ? trim((string)$parsed['seo_description']) : '',
        'model' => array(
            'id' => isset($model['id']) ? (int)$model['id'] : 0,
            'name' => isset($model['name']) ? (string)$model['name'] : ''
        )
    ), JSON_UNESCAPED_UNICODE);
} catch (Exception $e) {
    ob_end_clean();
    echo json_encode(array(
        'ok' => false,
        'error' => $e->getMessage()
    ), JSON_UNESCAPED_UNICODE);
}
