/**
 * LiteMall AI 通用技能生成路由
 * 
 * 支持所有Skill类型的文本生成任务
 * POST /api/ai-gen/generate
 * Body: { skill, prompt, context }
 * 
 * 返回：AI生成的纯文本内容
 */

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

router.use(authAdmin);

/**
 * AI 通用生成接口
 * POST /api/ai-gen/generate
 * Body: { skill, prompt, product_id, extra }
 */
router.post('/generate', async (req, res) => {
  try {
    const { skill, prompt, product_id, extra } = req.body;

    // 验证skill是否存在
    const allSkills = skillEngine.getSkillList();
    const validSkill = allSkills.find(s => s.id === skill);
    if (!validSkill) {
      const validNames = allSkills.map(s => `${s.id}(${s.name})`).join(', ');
      return res.json(fail(`无效的技能类型，可选：${validNames}`));
    }

    if (!prompt) return res.json(fail('请输入生成内容'));

    // 加载商品上下文（如果提供了product_id）
    let context = {};
    if (product_id) {
      try {
        const db = require('../utils/db');
        const product = db.get('SELECT id, name, category, price, keywords, sales FROM products WHERE id=?', [product_id]);
        if (product) {
          context.product_name = product.name;
          context.product_category = product.category || '未分类';
          context.product_price = product.price || 0;
          context.product_sales = product.sales || 0;
        }
      } catch (e) { /* 静默 */ }
    }

    // 合并额外上下文
    if (extra && typeof extra === 'object') {
      Object.assign(context, extra);
    }

    const reply = await chatWithSkill(skill, [
      { role: 'user', content: prompt }
    ], { context });

    // 记录调用日志
    try {
      run("INSERT INTO ai_assistant_logs(admin_id,type,input,output) VALUES(?,?,?,?)",
        [req.userId, `gen_${skill}`, prompt.substring(0, 200), reply.substring(0, 500)]);
    } catch (e) { /* 静默 */ }

    return res.json(success({ output: reply, skill: validSkill.name }));
  } catch (e) {
    return res.json(fail('生成失败: ' + e.message));
  }
});

/**
 * 获取所有可用技能列表（含描述）
 * GET /api/ai-gen/skills
 */
router.get('/skills', (req, res) => {
  const list = skillEngine.getSkillList();
  const enriched = list.map(s => {
    const raw = skillEngine.loadSkillRaw(s.id);
    const desc = raw.split('\n').find(l => l.startsWith('description:'))?.replace('description:', '').trim() || s.name;
    return { ...s, description: desc };
  });
  return res.json(success(enriched));
});

/**
 * 获取商品列表（供AI评价生成时选择）
 * GET /api/ai-gen/products
 */
router.get('/products', (req, res) => {
  const db = require('../utils/db');
  const { q, page = 1, pageSize = 50 } = req.query;
  let where = 'WHERE status=1';
  const params = [];
  if (q) { where += ' AND name LIKE ?'; params.push(`%${q}%`); }
  const count = db.get(`SELECT COUNT(*) as total FROM products ${where}`, params);
  const list = db.all(
    `SELECT id, name, price, stock, sales, image, category_id FROM products ${where} ORDER BY sales DESC LIMIT ? OFFSET ?`,
    [...params, pageSize, (Math.max(1, +page) - 1) * pageSize]
  );
  return res.json(success({
    list: list.map(p => ({ ...p, image: p.image ? (p.image.startsWith('http') ? p.image : '/uploads/' + p.image) : '' })),
    total: count?.total || 0,
  }));
});

/**
 * AI批量评价生成 + 自动入库
 * POST /api/ai-gen/reviews/batch-generate
 * Body: { product_id, count }
 */
router.post('/reviews/batch-generate', async (req, res) => {
  try {
    const { product_id, count = 3 } = req.body;
    if (!product_id) return res.json(fail('请选择商品'));
    
    const db = require('../utils/db');
    
    // 读取商品信息
    const product = db.get('SELECT id, name, category_id, price, seo_keywords FROM products WHERE id=? AND status=1', [product_id]);
    if (!product) return res.json(fail('商品不存在或已下架'));
    
    // AI生成评价
    const prompt = `为以下商品生成${Math.min(count, 10)}条买家评价：

商品：${product.name}
价格：¥${product.price || '?'}
分类ID：${product.category_id || '通用'}

要求：
1. 每条包含：昵称、规格、评分(1-5)、内容(20-60字)、口吻标签
2. 区分不同人群口吻（实用型/外貌型/专业型/随和型）
3. 内容自然真实，带使用场景，不夸大
4. 规避违规极限词
5. 用JSON数组格式输出，字段：nickname, sku_info, rating, content, type`;
    
    const reply = await chatWithSkill('review_after', [
      { role: 'user', content: prompt }
    ], { context: { product_name: product.name } });
    
    // 从AI输出中提取JSON
    let reviews = [];
    try {
      // 尝试直接解析
      const jsonMatch = reply.match(/\[\s*\{[\s\S]*?\}\s*\]/);
      if (jsonMatch) {
        reviews = JSON.parse(jsonMatch[0]);
      }
    } catch (e) {
      // 解析失败，按行拆分
      console.log('[AI评价] JSON解析失败，尝试行解析');
    }
    
    if (!Array.isArray(reviews) || reviews.length === 0) {
      // 兜底：按行解析
      const lines = reply.split('\n').filter(l => l.trim().length > 5);
      reviews = lines.slice(0, Math.min(count, 10)).map((line, i) => ({
        nickname: ['热心买家', '购物达人', '品质生活家', '数码控', '家居爱好者'][i % 5],
        sku_info: product.name,
        rating: [4, 5, 4, 3, 5][i % 5],
        content: line.replace(/^\d+[.、]?\s*/, '').substring(0, 100),
        type: '实用型',
      }));
    }
    
    // 限制条数
    reviews = reviews.slice(0, Math.min(count, 10));
    
    // 人工审核链路：AI生成评价不直接入库，先存入待审池
    // 软著要求：AI批量生成内容必须有强制人工审核节点
    // 依据：2026年市场监管总局公告，AI批量生成虚假用户评价属《网络反不正当竞争暂行规定》第12条违规
    // 待运营在「内容审核」页面确认通过后，评价才会写入商品评价表并展示
    const savedReviews = [];
    for (const r of reviews) {
      try {
        const sku = r.sku_info || r.spec || product.name;
        const rating = Math.max(1, Math.min(5, parseInt(r.rating) || 5));
        const content = (r.content || '好评，不错。').substring(0, 500);
        
        // 组装评价内容（含完整信息，供审核时查看）
        const reviewContent = JSON.stringify({
          product_id,
          product_name: product.name,
          sku_info: sku,
          rating,
          content,
          nickname: r.nickname || '匿名买家',
          type: r.type || '通用',
        });
        
        // 存入审核表
        const aiReview = require('./ai-review');
        const reviewId = aiReview.saveToReview({
          sourceType: 'review',
          sourceId: product_id,
          sourceName: product.name,
          content: reviewContent,
          requestInput: `商品:${product.name} 批量生成评价, count:${count}`,
          adminId: req.userId
        });
        
        savedReviews.push({
          review_id: reviewId,
          nickname: r.nickname || '匿名买家',
          sku_info: sku,
          rating,
          content,
          type: r.type || '通用',
        });
      } catch (e) {
        console.log('[AI评价] 存入待审池失败:', e.message);
      }
    }
    
    // 记录调用
    require('../utils/db').run(
      "INSERT INTO ai_assistant_logs(admin_id,type,input,output) VALUES(?,?,?,?)",
      [req.userId, 'reviews_batch', `product:${product.name} count:${count}`, reply.substring(0, 500)]
    );
    
    return res.json(success({
      product_name: product.name,
      generated: savedReviews.length,
      reviews: savedReviews,
      review_required: true,
      raw_output: reply,
    }, `已生成 ${savedReviews.length} 条评价，已进入待审池，请前往「内容审核」页面确认发布`));
    
  } catch (e) {
    return res.json(fail('评价生成失败: ' + e.message));
  }
});

module.exports = router;
