/**
 * LiteMall AI 商品助手路由（管理后台使用）
 * 
 * 双技能模式：
 * - skill_product_crawl: 货源采集 + 智能上架
 * - skill_product_seo: 商品标题/关键词/详情SEO优化
 * 
 * 权限：管理员
 */

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

router.use(authAdmin);

// ==================== 通用：调用次数记录 ====================

    // NOTE: logAiUsage 仅一次 INSERT，高频调用时可用批量写入优化；当前场景非高频，无需重构

function logAiUsage(adminId, skill, type, input, output) {
  try {
    run('INSERT INTO ai_assistant_logs(admin_id,type,input,output) VALUES(?,?,?,?)',
      [adminId, `${skill}_${type}`, (input || '').substring(0, 500), (output || '').substring(0, 1000)]);
  } catch (e) {
    console.error('[AI商品] 日志记录失败:', e.message);
  }
}

// ==================== AI 采集助手 ====================

/**
 * AI 辅助采集：解析商品链接（优先调真实采集API，无key则AI生成）
 * POST /api/ai-product/crawl-suggest
 * Body: { url, platform, keywords }
 */
router.post('/crawl-suggest', async (req, res) => {
  try {
    const { url, platform, keywords } = req.body;
    if (!url && !keywords) return res.json(fail('请提供商品链接或搜索关键词'));

    // 如果有链接，尝试调真实采集接口
    let realData = null;
    if (url) {
      try {
        const { fetchYihaotong } = require('./collect');
        const { get, all } = require('../utils/db');
        const cfgRows = all("SELECT \`key\`, \`value\` FROM system_config WHERE \`key\` LIKE 'collect_%'");
        const cfg = {};
        cfgRows.forEach(r => { cfg[r.key.replace('collect_', '')] = r.value; });
        
        if (cfg.app_key) {
          realData = await fetchYihaotong(url, cfg.app_key, cfg.app_secret || '');
        }
      } catch (e) {
        console.log('[采集] 真实API调用失败，走AI兜底:', e.message);
      }
    }

    if (realData) {
      // 真实API返回了数据 → AI做二次优化
      const aiOptimized = await chatWithSkill('product_crawl', [
        { role: 'user', content: `以下是通过采集API获取的商品数据，请优化标题和定价：

标题：${realData.title}
原价：¥${realData.original_price}
规格：${JSON.stringify(realData.specs)}

输出优化后的JSON，包含title, price, spec_list, desc, audit_tips字段` }
      ]);
      return res.json(success({
        source: 'api',
        raw: realData,
        ai_suggestion: aiOptimized,
      }, '已从真实采集接口获取数据'));
    }

    // 无真实API → AI生成
    const input = url ? `链接：${url}（平台：${platform || '自动识别'}）` : `关键词：${keywords}`;
    const reply = await chatWithSkill('product_crawl', [
      { role: 'user', content: `我需要从以下来源采集商品：\n${input}\n\n请分析：\n1. 这个商品可能的分类是什么\n2. 上架定价建议（加价率30%左右）\n3. 标题优化建议` }
    ]);

    logAiUsage(req.userId, 'product_crawl', 'suggest', input, reply);
    return res.json(success({ source: 'ai', suggestion: reply, missing_field: ['需配置采集API Key才能获取真实商品数据'] }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 生成商品详情
 * POST /api/ai-product/generate-detail
 * Body: { name, price, category, features }
 */
router.post('/generate-detail', async (req, res) => {
  try {
    const { name, price, category, features } = req.body;
    if (!name) return res.json(fail('请提供商品名称'));

    const reply = await chatWithSkill('product_crawl', [
      { role: 'user', content: `为以下商品生成上架用的完整详情描述：\n\n名称：${name}\n价格：¥${price || '待定'}\n分类：${category || '未分类'}\n特点：${features || '普通商品'}\n\n要求：\n1. 包含商品描述、规格参数、使用说明\n2. 突出核心卖点\n3. 150-300字，纯文本` }
    ]);

    logAiUsage(req.userId, 'product_crawl', 'detail', name, reply);
    return res.json(success({ content: reply }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 定价建议
 * POST /api/ai-product/price-suggest
 * Body: { cost_price, platform, category }
 */
router.post('/price-suggest', async (req, res) => {
  try {
    const { cost_price, platform, category } = req.body;
    if (!cost_price) return res.json(fail('请提供成本价'));

    const reply = await chatWithSkill('product_crawl', [
      { role: 'user', content: `商品定价建议：\n成本价：¥${cost_price}\n来源平台：${platform || '未知'}\n品类：${category || '未知'}\n\n请给出：建议售价、最低售价、推荐售价区间。` }
    ]);

    logAiUsage(req.userId, 'product_crawl', 'price', cost_price.toString(), reply);
    return res.json(success({ suggestion: reply }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

// ==================== AI SEO 优化助手 ====================

/**
 * AI 标题优化
 * POST /api/ai-product/seo-title
 * Body: { product_id, title, category }
 */
router.post('/seo-title', async (req, res) => {
  try {
    const { product_id, title, category } = req.body;
    if (!title) return res.json(fail('请提供原标题'));

    const reply = await chatWithSkill('product_seo', [
      { role: 'user', content: `优化商品标题（搜索引擎友好）：\n\n原标题：${title}\n分类：${category || '未分类'}\n\n要求：\n1. 核心关键词前置\n2. 不超过30字\n3. 给出3个可选方案\n4. 标注每个方案的优化点` }
    ]);

    logAiUsage(req.userId, 'product_seo', 'title', title, reply);

    // 如果有product_id，保存到seo建议表
    if (product_id) {
    }

    return res.json(success({ suggestions: reply }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 关键词优化
 * POST /api/ai-product/seo-keywords
 * Body: { product_id, name, category }
 */
router.post('/seo-keywords', async (req, res) => {
  try {
    const { name, category } = req.body;
    if (!name) return res.json(fail('请提供商品名称'));

    const reply = await chatWithSkill('product_seo', [
      { role: 'user', content: `为以下商品生成SEO关键词：\n\n商品名称：${name}\n分类：${category || '未分类'}\n\n请提供：\n1. 5个核心关键词\n2. 5个长尾关键词\n3. TDK标题（≤30字）\n4. Meta Description（≤80字）` }
    ]);

    logAiUsage(req.userId, 'product_seo', 'keywords', name, reply);
    return res.json(success({ content: reply }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 批量SEO诊断
 * POST /api/ai-product/seo-audit
 * Body: { product_ids } 或 { page=1, pageSize=20 }
 */
router.post('/seo-audit', async (req, res) => {
  try {
    const { product_ids } = req.body;
    let products;

    if (product_ids && Array.isArray(product_ids)) {
      const placeholders = product_ids.map(() => '?').join(',');
      products = all(`SELECT id, name, category, keywords FROM products WHERE id IN (${placeholders})`, product_ids);
    } else {
      products = all('SELECT id, name, category, keywords FROM products ORDER BY sales DESC LIMIT 20');
    }

    if (!products || products.length === 0) {
      return res.json(fail('没有找到商品'));
    }

    // 分析商品标题质量
    const analysis = products.map(p => {
      const titleLen = (p.name || '').length;
      const hasKeywords = p.keywords && p.keywords.length > 0;
      return {
        id: p.id,
        name: p.name,
        issues: [
          titleLen < 10 ? '标题过短（<10字）' : null,
          titleLen > 40 ? '标题过长（>40字）' : null,
          !hasKeywords ? '缺少关键词' : null,
        ].filter(Boolean),
        score: titleLen >= 10 && titleLen <= 30 ? 80 : 50,
      };
    });

    const badTitles = analysis.filter(a => a.issues.length > 0);
    let aiSuggestion = '';
    
    if (badTitles.length > 0) {
      const sample = badTitles.slice(0, 3);
      aiSuggestion = await chatWithSkill('product_seo', [
        { role: 'user', content: `以下商品标题需要优化，请给出批量优化建议：\n${sample.map(s => `${s.id}. ${s.name}（问题：${s.issues.join('、')}）`).join('\n')}` }
      ]);
    }

    logAiUsage(req.userId, 'product_seo', 'audit', `${products.length}个商品`, aiSuggestion || '无需优化');

    return res.json(success({
      total: products.length,
      needOptimization: badTitles.length,
      avgScore: Math.round(analysis.reduce((s, a) => s + a.score, 0) / analysis.length),
      details: analysis,
      aiSuggestion,
    }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

// ==================== 技能文件管理 ====================

const skillEngine = require('../lib/skill-engine');

/**
 * 获取技能列表
 */
router.get('/skills', (req, res) => {
  const list = skillEngine.getSkillList();
  // 同时加载自定义提示词
  const enriched = list.map(s => ({
    ...s,
    custom_prompt: skillEngine.loadCustomPrompt(s.id, { get }) || '',
  }));
  return res.json(success(enriched));
});

/**
 * 读取技能文件内容
 */
router.get('/skills/:name', (req, res) => {
  const content = skillEngine.readSkillFile(req.params.name);
  if (content === undefined || content === null) {
    return res.json(fail('技能文件不存在'));
  }
  return res.json(success({ content }));
});

/**
 * 保存技能文件内容
 */
router.put('/skills/:name', (req, res) => {
  const { content } = req.body;
  if (!content) return res.json(fail('内容不能为空'));
  const result = skillEngine.writeSkillFile(req.params.name, content);
  if (!result.ok) return res.json(fail(result.message));
  return res.json(success(null, result.message));
});

/**
 * 保存自定义提示词（覆盖技能规则）
 */
router.post('/custom-prompt', (req, res) => {
  const { skill_name, prompt } = req.body;
  if (!skill_name) return res.json(fail('请指定技能名称'));

  try {
    const key = `ai_custom_prompt_${skill_name}`;
    const exist = get("SELECT id FROM system_config WHERE key=?", [key]);
    if (exist) {
      run("UPDATE system_config SET value=? WHERE key=?", [prompt || '', key]);
    } else {
      run("INSERT INTO system_config(key,value,type,description) VALUES(?,?,'textarea','AI技能自定义提示词')",
        [key, prompt || '']);
    }
    // 清除技能引擎缓存
    skillEngine.clearCache(skill_name);
    return res.json(success(null, '自定义提示词已保存'));
  } catch (e) {
    return res.json(fail('保存失败: ' + e.message));
  }
});

module.exports = router;
