<?php
/**
 * 根据标题调用已启用的 AI 模型生成文章 HTML
 * 输入：POST { title, keywords? }
 * 输出：JSON { ok, html, error, model }
 *
 * 登录态校验 + 输入长度限制，避免滥用。
 */
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

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

set_time_limit(120);

$title = isset($_POST['title']) ? trim((string)$_POST['title']) : '';
$keywords = isset($_POST['keywords']) ? trim((string)$_POST['keywords']) : '';
$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']) : '');
if ($siteLanguage === '') {
    $siteLanguage = 'auto';
}
$isEnglish = ($siteLanguage === 'en-US' || $siteLanguage === 'en-GB');

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

    // 选用启用的 AI 模型：优先请求指定的，其次取第一条启用
    $model = null;
    if ($modelId > 0) {
        $candidate = find_ai_model_by_id($modelId);
        if ($candidate && isset($candidate['status']) && $candidate['status'] === 'enabled') {
            $model = $candidate;
        }
    }
    if (!$model) {
        $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 content writer. Write a clear, natural English article body based on the provided title and keywords. Return HTML only, no Markdown, no code fences, and no extra explanation. Requirements: about 1000-1500 words; include at least 3 <h2> sections; use <p> paragraphs; use <ul><li> lists and <strong> emphasis when needed; avoid vague filler and keep the content practical and keyword-focused. If the title is in Chinese, translate the meaning into natural English SEO content rather than copying Chinese words.'
        : '你是一名中文 SEO 内容编辑。请根据用户提供的标题与关键词撰写一篇结构清晰、语义自然的文章正文。严格只返回 HTML 片段，不要使用 Markdown，不要输出代码块或多余解释。要求：文章长度约 1000-1500 字；至少包含 3 个 <h2> 小节；段落使用 <p>；必要时使用 <ul><li> 列表与 <strong> 强调；避免空洞套话，围绕关键词展开实用内容。';
    $userPrompt = '标题：' . $title . "\n站点语言：" . $siteLanguage . "\n强制要求：如果站点语言是英文，所有内容必须是英文。";
    if ($keywords !== '') {
        $userPrompt .= "\n关键词：" . $keywords;
    }

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

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

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

    if ($html === '') {
        throw new Exception('AI 返回为空，请稍后重试或检查模型可用性。');
    }

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