<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(array('error' => '仅支持 POST 请求。'));
    exit;
}

require_csrf();

$menuName = isset($_POST['menu_name']) ? trim((string)$_POST['menu_name']) : '';
$modelId  = isset($_POST['model_id']) ? (int)$_POST['model_id'] : 0;
$isHome   = isset($_POST['is_home']) && $_POST['is_home'] === '1';
$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']) ? normalize_domain_language($_POST['site_language']) : 'zh-CN');
$debugMode = (!empty($_POST['debug']) && (string)$_POST['debug'] !== '0') || (!empty($_GET['debug']) && (string)$_GET['debug'] !== '0');
$debugInfo = array(
    'domain_id' => $domainId,
    'site_language' => $siteLanguage,
    'is_home' => $isHome,
    'menu_name' => $menuName,
);

if ($menuName === '') {
    echo json_encode(array('error' => $isHome ? '请先选择域名。' : '请先填写菜单名称。'));
    exit;
}
if ($modelId < 1) {
    echo json_encode(array('error' => '请选择 AI 模型。'));
    exit;
}

try {
    $model = find_ai_model_by_id($modelId);
    if (!$model || $model['status'] !== 'enabled') {
        throw new Exception('所选模型不可用或已禁用。');
    }

    $isEnglish = ($siteLanguage === 'en-US' || $siteLanguage === 'en-GB');
    $langLabelMap = array(
        'zh-CN' => '中文（简体）',
        'zh-TW' => '中文（繁体）',
        'en-US' => 'English (US)',
        'en-GB' => 'English (UK)',
        'ja-JP' => '日本語',
        'ko-KR' => '한국어',
    );
    $langLabel = isset($langLabelMap[$siteLanguage]) ? $langLabelMap[$siteLanguage] : $siteLanguage;
    if ($isHome) {
        $systemPrompt = $isEnglish
            ? 'You are a strict multilingual SEO expert. The target site language is English. You MUST output English only. Generate SEO keywords and a meta description for a website homepage from the site name and domain meaning. Return JSON only with exactly two fields: keywords (5-8 English keywords separated by commas) and description (60-120 natural English words). Do not output any Chinese text, transliteration, or extra content. If the site name is Chinese, translate the meaning into English SEO terms instead of copying Chinese words.'
            : '你是一位专业的多语言SEO优化专家。用户会给你一个网站/品牌名称，你需要根据站点语言生成对应语言的首页SEO关键词和SEO描述。关键词必须严格使用当前站点语言，不要混用其他语言。请严格按JSON格式返回，包含两个字段：keywords（字符串，多个关键词用英文逗号分隔，5-8个关键词，必须与站点语言一致）和 description（字符串，60-120个当前站点语言字符的首页描述，要有吸引力并包含核心关键词）。不要返回任何其他内容。';
        $userPrompt = '站点名称：' . $menuName . "\n站点语言：" . $siteLanguage . '（' . $langLabel . "）\n强制要求：如果站点语言不是中文，所有返回内容必须严格使用当前站点语言。";
    } else {
        $systemPrompt = $isEnglish
            ? 'You are a strict multilingual SEO expert. The target site language is English. You MUST output English only. Generate SEO keywords and a meta description for a website section/menu from the menu name and site context. Return JSON only with exactly two fields: keywords (5-8 English keywords separated by commas) and description (60-120 natural English words). Do not output any Chinese text, transliteration, or extra content. If the menu name is Chinese, translate the meaning into English SEO terms instead of copying Chinese words.'
            : '你是一位专业的多语言SEO优化专家。用户会给你一个网站栏目/菜单名称，你需要根据站点语言生成对应语言的栏目SEO关键词和栏目SEO描述。关键词必须严格使用当前站点语言，不要混用其他语言。请严格按JSON格式返回，包含两个字段：keywords（字符串，多个关键词用英文逗号分隔，5-8个关键词，必须与站点语言一致）和 description（字符串，60-120个当前站点语言字符的栏目描述，要有吸引力并包含核心关键词）。不要返回任何其他内容。';
        $userPrompt = '栏目名称：' . $menuName . "\n站点语言：" . $siteLanguage . '（' . $langLabel . "）\n强制要求：如果站点语言不是中文，所有返回内容必须严格使用当前站点语言。";
    }

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

    if ($debugMode) {
        echo json_encode(array(
            'debug' => true,
            'instructions' => array(
                'system_prompt' => $systemPrompt,
                'user_prompt' => $userPrompt,
                'site_language' => $siteLanguage,
                'domain_id' => $domainId,
                'menu_name' => $menuName,
                'is_home' => $isHome
            )
        ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $maxAttempts = 2;
    $keywords = '';
    $description = '';

    for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
        $aiResult = execute_ai_generation_request($model, $messages, true);
        $aiText = isset($aiResult['assistant_text']) ? (string)$aiResult['assistant_text'] : '';

        $cleaned = preg_replace('/^```(?:json)?\s*/i', '', trim($aiText));
        $cleaned = preg_replace('/\s*```$/i', '', $cleaned);

        $parsed = json_decode($cleaned, true);

        if (!is_array($parsed)) {
            if ($attempt >= $maxAttempts) {
                throw new Exception('AI 返回格式异常，无法解析。原始内容：' . mb_substr($aiText, 0, 200));
            }
            continue;
        }

        $keywords    = isset($parsed['keywords'])    ? trim((string)$parsed['keywords'])    : '';
        $description = isset($parsed['description']) ? trim((string)$parsed['description']) : '';

        $kwList = array_filter(array_map('trim', preg_split('/[,，、;；]+/', $keywords)));
        if (count($kwList) >= 3) {
            break;
        }

        if ($attempt < $maxAttempts) {
            $retryPrompt = $isEnglish
                ? ($isHome
                    ? 'You are a professional SEO expert. Generate SEO keywords and a meta description for a website homepage. Return JSON only with two fields: keywords (5-8 English keywords separated by commas) and description (60-120 natural English words). Do not output any Chinese text or any extra content. The keywords must be distinct English terms, not Chinese.'
                    : 'You are a professional SEO expert. Generate SEO keywords and a meta description for a website section/menu. Return JSON only with two fields: keywords (5-8 English keywords separated by commas) and description (60-120 natural English words). Do not output any Chinese text or any extra content. The keywords must be distinct English terms, not Chinese.')
                : ($isHome
                    ? '你是一位专业的中文SEO优化专家。请为以下网站首页生成SEO信息。注意：keywords字段必须包含5到8个不同的中文关键词，用英文逗号分隔。绝对不能只返回1-2个关键词，必须至少5个。请严格按JSON格式返回，包含keywords和description两个字段。不要返回任何其他内容。'
                    : '你是一位专业的中文SEO优化专家。请为以下网站栏目生成SEO信息。注意：keywords字段必须包含5到8个不同的中文关键词，用英文逗号分隔。绝对不能只返回1-2个关键词，必须至少5个。请严格按JSON格式返回，包含keywords和description两个字段。不要返回任何其他内容。');
            $messages = array(
                array('role' => 'system', 'content' => $retryPrompt),
                array('role' => 'user', 'content' => ($isHome ? '站点名称：' : '栏目名称：') . $menuName . "\n站点语言：" . $siteLanguage . "\n\n请注意：上次返回的关键词数量不符合要求。这次请务必返回5-8个不同的" . ($isEnglish ? 'English' : '中文') . '关键词。')
            );
        }
    }

    echo json_encode(array(
        'success'     => true,
        'keywords'    => $keywords,
        'description' => $description
    ), JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    echo json_encode(array('error' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
}
