/**
 * LiteMall AI 自定义提示词管理路由
 * 
 * 功能：
 * - 每个技能独立存放自定义提示词
 * - 输入过滤（自动清除提示词注入）
 * - 「重置默认模板」删除自定义提示词
 * - 「测试AI输出」实时预览
 * 
 * 数据表：ai_prompts（优先）/ system_config（回退）
 */

const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail } = require('../utils/response');
const { authAdmin } = require('../middleware/auth');
const skillEngine = require('../lib/skill-engine');
const { chatWithSkill } = require('../lib/ai-client');

router.use(authAdmin);

/**
 * 获取所有技能的自定义提示词
 * GET /api/ai-prompt/list
 */
router.get('/list', (req, res) => {
  const skills = skillEngine.getSkillList();
  const result = skills.map(s => {
    let prompt = '';
    try {
      const row = get("SELECT custom_prompt FROM ai_prompts WHERE skill=? ORDER BY id DESC LIMIT 1", [s.id]);
      if (row) prompt = row.custom_prompt || '';
      if (!prompt) {
        const fallback = get("SELECT value FROM system_config WHERE key=?", [`ai_custom_prompt_${s.id}`]);
        prompt = fallback ? (fallback.value || '') : '';
      }
    } catch (e) { /* 静默 */ }
    return { ...s, custom_prompt: prompt };
  });
  return res.json(success(result));
});

/**
 * 保存自定义提示词
 * POST /api/ai-prompt/save
 * Body: { skill, prompt }
 */
router.post('/save', (req, res) => {
  const { skill, prompt } = req.body;
  if (!skill) return res.json(fail('请指定技能名称'));

  // 输入过滤（清除提示词注入）
  const cleaned = skillEngine.sanitizePrompt(prompt || '');

  try {
    // 写入 ai_prompts 表
    const existing = get("SELECT id FROM ai_prompts WHERE skill=?", [skill]);
    if (existing) {
      run("UPDATE ai_prompts SET custom_prompt=?, updated_at=datetime('now','localtime') WHERE skill=?", [cleaned, skill]);
    } else {
      run("INSERT INTO ai_prompts(skill,custom_prompt) VALUES(?,?)", [skill, cleaned]);
    }

    // 同步写入 system_config（兼容旧版读取）
    const key = `ai_custom_prompt_${skill}`;
    const cfg = get("SELECT id FROM system_config WHERE key=?", [key]);
    if (cfg) {
      run("UPDATE system_config SET value=? WHERE key=?", [cleaned, key]);
    } else {
      run("INSERT INTO system_config(key,value,type,description) VALUES(?,?,'textarea','AI技能自定义提示词')", [key, cleaned]);
    }

    // 清除技能引擎缓存
    skillEngine.clearCache(skill);

    return res.json(success({ filtered: cleaned !== (prompt || '') }, cleaned !== (prompt || '') ? '已过滤违规指令并保存' : '保存成功'));
  } catch (e) {
    return res.json(fail('保存失败: ' + e.message));
  }
});

/**
 * 重置自定义提示词（删除）
 * POST /api/ai-prompt/reset
 * Body: { skill }
 */
router.post('/reset', (req, res) => {
  const { skill } = req.body;
  if (!skill) return res.json(fail('请指定技能名称'));

  try {
    run("DELETE FROM ai_prompts WHERE skill=?", [skill]);
    const key = `ai_custom_prompt_${skill}`;
    run("DELETE FROM system_config WHERE key=?", [key]);
    skillEngine.clearCache(skill);
    return res.json(success(null, '已恢复默认模板'));
  } catch (e) {
    return res.json(fail('重置失败: ' + e.message));
  }
});

/**
 * 测试AI输出（实时调用AI接口预览效果）
 * POST /api/ai-prompt/test
 * Body: { skill, prompt, test_input }
 */
router.post('/test', async (req, res) => {
  try {
    const { skill, prompt, test_input } = req.body;
    if (!skill) return res.json(fail('请指定技能'));
    if (!test_input) return res.json(fail('请输入测试内容'));

    // 先保存到 ai_prompts 表（临时）
    const existing = get("SELECT id FROM ai_prompts WHERE skill=?", [skill]);
    const cleaned = skillEngine.sanitizePrompt(prompt || '');
    if (existing) {
      run("UPDATE ai_prompts SET custom_prompt=?, updated_at=datetime('now','localtime') WHERE skill=?", [cleaned, skill]);
    } else {
      run("INSERT INTO ai_prompts(skill,custom_prompt) VALUES(?,?)", [skill, cleaned]);
    }
    skillEngine.clearCache(skill);

    // 调用AI
    const reply = await chatWithSkill(skill, [
      { role: 'user', content: test_input }
    ]);

    // 输出过滤（合规兜底）
    const filtered = skillEngine.filterOutput(reply);

    return res.json(success({
      output: filtered,
      filtered: filtered !== reply,
    }));
  } catch (e) {
    return res.json(fail('AI测试失败: ' + e.message));
  }
});

/**
 * 获取 AI 配置
 * GET /api/ai-prompt/config
 */
router.get('/config', (req, res) => {
  const apiKey = get("SELECT value FROM system_config WHERE key='ai_api_key'")?.value || '';
  const apiUrl = get("SELECT value FROM system_config WHERE key='ai_api_url'")?.value || 'https://api.deepseek.com/v1/chat/completions';
  const model = get("SELECT value FROM system_config WHERE key='ai_model'")?.value || 'deepseek-chat';
  const aiEnabled = get("SELECT value FROM system_config WHERE key='ai_enabled'")?.value || '0';
  const aiUseModel = get("SELECT value FROM system_config WHERE key='ai_use_model'")?.value || '0';
  
  return res.json(success({
    api_key_preview: apiKey ? apiKey.substring(0, 8) + '****' : '',
    api_key_configured: !!apiKey,
    api_url: apiUrl,
    model,
    ai_enabled: aiEnabled,
    ai_use_model: aiUseModel,
  }));
});

/**
 * 保存 AI 配置
 * POST /api/ai-prompt/config
 * Body: { api_key, api_url, model, ai_enabled, ai_use_model }
 */
router.post('/config', (req, res) => {
  try {
    const { api_key, api_url, model, ai_enabled, ai_use_model } = req.body;
    
    const upsert = (key, value) => {
      if (value === undefined) return;
      const exist = get("SELECT id FROM system_config WHERE key=?", [key]);
      if (exist) {
        run("UPDATE system_config SET value=? WHERE key=?", [String(value), key]);
      } else {
        run("INSERT INTO system_config(key,value,type) VALUES(?,?,'text')", [key, String(value)]);
      }
    };
    
    upsert('ai_api_key', api_key);
    upsert('ai_api_url', api_url);
    upsert('ai_model', model);
    upsert('ai_enabled', ai_enabled);
    upsert('ai_use_model', ai_use_model);
    
    return res.json(success(null, 'AI 配置已保存'));
  } catch (e) {
    return res.json(fail('保存失败: ' + e.message));
  }
});

module.exports = router;
