<?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();

$keyword = isset($_POST['keyword']) ? trim((string)$_POST['keyword']) : '';
$modelId = isset($_POST['model_id']) ? (int)$_POST['model_id'] : 0;
$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']) : 'zh-CN');
$isEnglish = ($siteLanguage === 'en-US' || $siteLanguage === 'en-GB');

if ($keyword === '') {
    echo json_encode(array('error' => '请先填写核心关键词。'));
    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('所选模型不可用或已禁用。');
    }

    $messages = array(
        array(
            'role' => 'system',
            'content' => $isEnglish
                ? 'You are a professional website strategist. The target site language is English. Generate a concise, persuasive homepage description in natural English based on the core business keyword. The text must be English only, must not use JSON, and must not include any labels or markdown. Keep it under 160 English words/characters and make sure the keyword is naturally included.'
                : '你是一位专业的企业网站策划师。用户会给你一个核心业务关键词，你需要根据这个关键词生成一段适合企业网站首页的站点seo描述。开头中间结尾自然融入核心关键词，请直接返回纯文本描述，不超过160个中文字符，不要使用JSON格式，不要加任何标记。语言要专业、有吸引力，适合用于AI生成企业网站首页内容。'
        ),
        array(
            'role' => 'user',
            'content' => '核心关键词：' . $keyword . "\n站点语言：" . $siteLanguage . "\n强制要求：如果站点语言是英文，所有返回内容必须是英文。"
        )
    );

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

    if ($aiText === '') {
        throw new Exception('AI 未返回有效内容。');
    }

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

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