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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json; charset=utf-8');
    http_response_code(405);
    echo json_encode(array('ok' => false, 'error' => 'Method Not Allowed'));
    exit;
}

require_csrf();

$keyword  = isset($_POST['keyword'])  ? trim((string)$_POST['keyword'])  : '';
$count    = isset($_POST['count'])    ? (int)$_POST['count']              : 0;
$modelId  = isset($_POST['model_id']) ? (int)$_POST['model_id']           : 0;
$siteLanguage = isset($_POST['site_language']) ? trim((string)$_POST['site_language']) : 'zh-CN';
$siteLanguage = normalize_domain_language($siteLanguage);

// 参数校验阶段用 JSON 返回
function json_error($msg) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array('ok' => false, 'error' => $msg));
    exit;
}

if ($keyword === '') {
    json_error('请输入行业关键词。');
}
if ($count < 1 || $count > 200) {
    json_error('数量需在 1~200 之间。');
}

try {
    if ($modelId > 0) {
        $model = find_ai_model_by_id($modelId);
        if (!$model || (isset($model['status']) && $model['status'] !== 'enabled')) {
            json_error('所选AI模型不可用或已停用。');
        }
    } else {
        $model = find_first_enabled_ai_model();
    }
    if (!$model) {
        json_error('未配置可用的AI模型，请先在AI模型管理中添加并启用。');
    }

    $apiUrl = isset($model['api_url']) ? trim((string)$model['api_url']) : '';
    $apiKey = isset($model['api_key']) ? trim((string)$model['api_key']) : '';

    if ($apiUrl === '' || $apiKey === '') {
        json_error('AI模型配置不完整，请检查 API 地址和 Key。');
    }

    $langLabelMap = array(
        'zh-CN' => '中文（简体）',
        'zh-TW' => '中文（繁体）',
        'en-US' => 'English (US)',
        'en-GB' => 'English (UK)',
        'ja-JP' => '日本語',
        'ko-KR' => '한국어',
    );
    $langLabel = isset($langLabelMap[$siteLanguage]) ? $langLabelMap[$siteLanguage] : 'auto';
    $systemPrompt = 'You are a multilingual brand naming assistant. Output one name per line only and do not output any extra text.';
    if ($siteLanguage === 'zh-CN' || $siteLanguage === 'zh-TW') {
        $systemPrompt = '你是一个多语言品牌命名助手。每行输出一个名称，不要输出其他任何文字。';
    }

    if ($siteLanguage === 'en-US' || $siteLanguage === 'en-GB') {
        $prompt = 'You are a professional brand naming expert. Based on the following industry keyword, generate ' . $count . ' unique English website/site names.'
            . "\n\nRequirements:\n"
            . "1. Each name should be 2~4 English words or a short brandable phrase\n"
            . "2. Names must be unique, varied, concise, and easy to remember\n"
            . "3. Suitable as a website or business brand name\n"
            . "4. Do not use Chinese text, numbers, symbols, or trademarked brand names\n"
            . "5. Output one name per line only, no numbering, no explanation\n\n"
            . "Industry keyword: " . $keyword . "\n\n"
            . "Please output names line by line in English only:";
    } elseif ($siteLanguage === 'ja-JP') {
        $prompt = 'あなたはプロのブランドネーミング専門家です。以下の業界キーワードに基づいて、' . $count . ' 個の日本語サイト名を生成してください。'
            . "\n\n要件:\n"
            . "1. 各名称は 2〜6 文字程度の自然な日本語または短いブランド表現にする\n"
            . "2. 名前は重複しないこと、読みやすく覚えやすいこと\n"
            . "3. 企業サイト・業界サイトのブランド名として適していること\n"
            . "4. 中国語、数字、記号、商標名は使用しないこと\n"
            . "5. 1 行に 1 つだけ出力し、番号や説明は不要\n\n"
            . "業界キーワード: " . $keyword . "\n\n"
            . "日本語のみで行ごとに出力してください。";
    } elseif ($siteLanguage === 'ko-KR') {
        $prompt = '당신은 전문 브랜드 네이밍 전문가입니다. 아래 업종 키워드를 바탕으로 ' . $count . '개의 한국어 사이트 이름을 생성하세요.'
            . "\n\n요구사항:\n"
            . "1. 각 이름은 2~6자 정도의 자연스러운 한국어 또는 짧은 브랜드 표현이어야 함\n"
            . "2. 이름은 서로 중복되면 안 되며, 읽기 쉽고 기억하기 쉬워야 함\n"
            . "3. 기업 사이트/업종 사이트의 브랜드명으로 적합해야 함\n"
            . "4. 중국어, 숫자, 기호, 상표명은 사용하지 말 것\n"
            . "5. 한 줄에 하나씩만 출력하고 번호나 설명은不要\n\n"
            . "업종 키워드: " . $keyword . "\n\n"
            . "한국어만 사용하여 줄마다 출력하세요.";
    } else {
        $prompt = '你是一个专业的品牌命名专家。请根据以下行业关键词，生成' . $count . '个独特的网站名称（站点名）。'
            . "\n\n要求：\n"
            . "1. 每个名称使用当前站点语言自然表达，长度适中\n"
            . "2. 名称之间不可重复，风格多样化，简洁大气、朗朗上口\n"
            . "3. 适合作为企业或行业网站的品牌名\n"
            . "4. 严禁使用其他语言、数字和符号拼凑\n"
            . "5. 每行只输出一个名称，不要编号，不要加任何标记或解释\n\n"
            . "行业关键词：" . $keyword . "\n\n"
            . "请直接逐行输出名称，仅使用当前站点语言（" . $langLabel . '）。';
    }

    $payload = array(
        'model' => isset($model['model_name']) ? $model['model_name'] : 'deepseek-chat',
        'messages' => array(
            array('role' => 'system', 'content' => $systemPrompt),
            array('role' => 'user', 'content' => $prompt . "\n站点语言：" . $siteLanguage)
        ),
        'temperature' => 0.9,
        'stream' => true
    );

    $modelKey = isset($model['request_headers']) ? trim((string)$model['request_headers']) : '';
    if ($modelKey === 'deepseek-reasoner' || (isset($model['model_name']) && $model['model_name'] === 'deepseek-reasoner')) {
        $payload['thinking'] = array('type' => 'enabled');
    }

    $payloadJson = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    $curlHeaders = array(
        'Content-Type: application/json',
        'Accept: text/event-stream',
        'Authorization: Bearer ' . $apiKey
    );

    // 切换为 SSE 流式输出 —— 必须彻底关闭所有缓冲
    @ini_set('zlib.output_compression', '0');
    @ini_set('output_buffering', '0');
    @ini_set('implicit_flush', '1');
    if (function_exists('apache_setenv')) {
        @apache_setenv('no-gzip', '1');
    }
    // 清除所有 PHP 输出缓冲层
    while (ob_get_level() > 0) {
        ob_end_clean();
    }

    header('Content-Type: text/event-stream; charset=utf-8');
    header('Cache-Control: no-cache, no-store');
    header('Connection: keep-alive');
    header('X-Accel-Buffering: no');

    // 发送填充注释 + 初始事件，撑过 Nginx fastcgi 缓冲区 (默认 4K/8K)
    echo ':' . str_repeat(' ', 4096) . "\n\n";
    echo "data: " . json_encode(array('type' => 'start'), JSON_UNESCAPED_UNICODE) . "\n\n";
    flush();

    $fullText = '';
    $sseBuffer = '';
    $upstreamDone = false;

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payloadJson);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

    // 流式回调：逐块读取 AI 返回并实时转发给浏览器
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) use (&$fullText, &$sseBuffer, &$upstreamDone) {
        $sseBuffer .= $data;
        // SSE 数据以 \n\n 分割，逐条处理完整行
        while (($pos = strpos($sseBuffer, "\n")) !== false) {
            $line = substr($sseBuffer, 0, $pos);
            $sseBuffer = substr($sseBuffer, $pos + 1);
            $line = trim($line);
            if ($line === '') {
                continue;
            }
            if ($line === 'data: [DONE]') {
                $upstreamDone = true;
                return 0;
            }
            if (strpos($line, 'data: ') === 0) {
                $json = json_decode(substr($line, 6), true);
                if (!is_array($json)) {
                    continue;
                }
                if (isset($json['error']['message'])) {
                    echo "data: " . json_encode(array('type' => 'error', 'text' => $json['error']['message'])) . "\n\n";
                    flush();
                    continue;
                }
                $delta = '';
                if (isset($json['choices'][0]['delta']['content'])) {
                    $delta = (string)$json['choices'][0]['delta']['content'];
                }
                if ($delta !== '') {
                    $fullText .= $delta;
                    echo "data: " . json_encode(array('type' => 'chunk', 'text' => $delta), JSON_UNESCAPED_UNICODE) . "\n\n";
                    flush();
                }
            }
        }
        return strlen($data);
    });

    $curlResult = curl_exec($ch);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlResult === false && $fullText === '' && !$upstreamDone) {
        echo "data: " . json_encode(array('type' => 'error', 'text' => 'AI 接口请求失败：' . $curlError)) . "\n\n";
        flush();
        exit;
    }

    // 流结束，解析完整文本为名称列表
    $fullText = trim($fullText);
    // 去除模型可能输出的思考标签
    $cleanedText = preg_replace('/<think>[\s\S]*?<\/think>/i', '', $fullText);
    // 去除 markdown 代码块包裹
    $cleanedText = preg_replace('/```(?:json)?\s*([\s\S]*?)```/', '$1', $cleanedText);
    $cleanedText = trim($cleanedText);

    $names = array();

    // 优先尝试 JSON 数组解析（兼容仍输出 JSON 的模型）
    $jsonTry = json_decode($cleanedText, true);
    if (is_array($jsonTry) && !empty($jsonTry)) {
        $names = $jsonTry;
    }
    if (empty($names) && preg_match('/\[[\s\S]*\]/', $cleanedText, $m)) {
        $jsonTry = json_decode($m[0], true);
        if (is_array($jsonTry) && !empty($jsonTry)) {
            $names = $jsonTry;
        }
    }

    // 主路径：按行分割（适配纯文本逐行输出）
    if (empty($names)) {
        $lines = preg_split('/[\r\n、，,；;]+/', $cleanedText);
        foreach ($lines as $line) {
            $line = trim($line);
            // 去除编号前缀如 "1." "2）" "- "
            $line = preg_replace('/^\d+[\.\)、）]\s*/', '', $line);
            $line = preg_replace('/^[-–—·•]\s*/', '', $line);
            $line = trim($line, ' "\'""\'\'');
            if ($line !== '' && mb_strlen($line, 'UTF-8') >= 2 && mb_strlen($line, 'UTF-8') <= 20) {
                $names[] = $line;
            }
        }
    }

    if (empty($names)) {
        echo "data: " . json_encode(array('type' => 'error', 'text' => 'AI 返回格式异常，请重试。原始文本：' . mb_substr($fullText, 0, 200, 'UTF-8')), JSON_UNESCAPED_UNICODE) . "\n\n";
        flush();
        exit;
    }

    // 过滤和清洗
    $cleaned = array();
    foreach ($names as $n) {
        $n = trim((string)$n);
        if ($n !== '' && mb_strlen($n, 'UTF-8') <= 20) {
            $cleaned[] = $n;
        }
    }

    while (count($cleaned) < $count) {
        $cleaned[] = $keyword . mt_rand(100, 999);
    }
    $cleaned = array_slice($cleaned, 0, $count);

    // 发送最终解析结果
    echo "data: " . json_encode(array('type' => 'done', 'names' => $cleaned), JSON_UNESCAPED_UNICODE) . "\n\n";
    flush();

} catch (Exception $e) {
    // 如果已经开始 SSE，用 SSE 格式返回错误
    if (headers_sent()) {
        echo "data: " . json_encode(array('type' => 'error', 'text' => '生成失败，请稍后重试。')) . "\n\n";
        flush();
    } else {
        json_error('生成失败，请稍后重试。');
    }
}
