/**
 * LiteMall AI 客服路由（前端用户使用）
 * 
 * 技能：skill_customer_service
 * 说明：使用三层架构(Skill Engine)驱动的AI客服
 * - Layer 1: IDENTITY.md 全局身份
 * - Layer 2: skill_customer_service.md 客服技能
 * - Layer 3: 商家自定义提示词（可覆盖）
 */

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

router.use(authUser);

// ==================== 对话管理 ====================

// 创建会话
router.post('/conversation', (req, res) => {
  const r = run('INSERT INTO chat_conversations(user_id) VALUES(?)', [req.userId]);
  return res.json(success({ id: r.lastInsertRowid }, '创建成功'));
});

// 会话列表
router.get('/conversations', (req, res) => {
  const list = all('SELECT * FROM chat_conversations WHERE user_id=? ORDER BY id DESC LIMIT 20', [req.userId]);
  return res.json(success(list));
});

// 获取消息
router.get('/messages/:convId', (req, res) => {
  const { page: p = 1, pageSize = 50 } = req.query;
  const msgs = all('SELECT * FROM chat_messages WHERE conversation_id=? ORDER BY id ASC LIMIT ? OFFSET ?',
    [req.params.convId, pageSize, (Math.max(1, +p) - 1) * pageSize]);
  return res.json(success(msgs));
});

// 删除会话
router.delete('/conversation/:id', (req, res) => {
  run('DELETE FROM chat_messages WHERE conversation_id=?', [req.params.id]);
  run('DELETE FROM chat_conversations WHERE id=? AND user_id=?', [req.params.id, req.userId]);
  return res.json(success(null, '删除成功'));
});

// ==================== AI 智能回复（核心）====================

router.post('/message', async (req, res) => {
  try {
    const { conversation_id, content } = req.body;
    if (!content) return res.json(fail('消息不能为空'));

    // 保存用户消息
    run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
      [conversation_id, 'user', content]);

    // 检查AI开关
    const aiEnabled = get("SELECT value FROM system_config WHERE key='ai_enabled'")?.value;
    if (aiEnabled !== '1') {
      const reply = get("SELECT value FROM system_config WHERE key='ai_welcome'")?.value || 'AI客服暂未开启，请联系人工客服。';
      run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
        [conversation_id, 'assistant', reply]);
      return res.json(success({ reply }, '发送成功'));
    }

    // 免费版日限量检查
    const aiLimitCheck = checkAiDailyLimit();
    if (!aiLimitCheck.ok) {
      run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
        [conversation_id, 'assistant', aiLimitCheck.message]);
      return res.json(success({ reply: aiLimitCheck.message }, '发送成功'));
    }

    // --- 先用知识库匹配 ---
    const matched = all(`SELECT answer FROM ai_knowledge_base WHERE status=1 AND (
      question LIKE ? OR keywords LIKE ? OR ? LIKE question
    ) ORDER BY weight DESC LIMIT 1`,
      [`%${content}%`, `%${content}%`, content]);

    if (matched.length > 0 && matched[0].answer) {
      // 知识库命中，直接返回
      const reply = matched[0].answer;
      run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
        [conversation_id, 'assistant', reply]);
      return res.json(success({ reply, source: 'knowledge' }, '发送成功'));
    }

    // --- 知识库未命中 → 调用大模型（带客服技能上下文）---
    const useModel = get("SELECT value FROM system_config WHERE key='ai_use_model'")?.value;
    
    if (useModel !== '1') {
      // 未开启大模型，走兜底
      const fallback = get("SELECT value FROM system_config WHERE key='ai_auto_reply'")?.value === '1'
        ? (get("SELECT value FROM system_config WHERE key='ai_fallback'")?.value || '您好，请稍等，我将为您转接人工客服。')
        : '您好，已收到您的消息，我们会尽快回复。';
      run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
        [conversation_id, 'assistant', fallback]);
      return res.json(success({ reply: fallback, source: 'fallback' }, '发送成功'));
    }

    // 构造对话上下文（最近10轮）
    const recentMsgs = all(`
      SELECT role, content FROM chat_messages 
      WHERE conversation_id=? ORDER BY id DESC LIMIT 10
    `, [conversation_id]).reverse();

    // 获取用户信息丰富上下文
    const user = get("SELECT nickname, level_id FROM users WHERE id=?", [req.userId]);
    const userLevel = user ? get("SELECT name, discount FROM user_levels WHERE id=?", [user.level_id]) : null;

    const context = {
      user_name: user?.nickname || '用户',
      user_level: userLevel?.name || '普通用户',
      user_discount: userLevel?.discount || 1,
    };

    try {
      const reply = await chatWithSkill('customer_service', recentMsgs.map(m => ({
        role: m.role,
        content: m.content,
      })), { context });

      run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
        [conversation_id, 'assistant', reply]);
      return res.json(success({ reply, source: 'ai' }, '发送成功'));
    } catch (e) {
      // AI调用失败，走兜底回复
      console.error('[AI客服] 大模型调用失败:', e.message);
      const fallback = '抱歉，AI服务暂时不可用，请稍后再试或联系人工客服。';
      run('INSERT INTO chat_messages(conversation_id,role,content) VALUES(?,?,?)',
        [conversation_id, 'assistant', fallback]);
      return res.json(success({ reply: fallback, source: 'error_fallback' }, '发送成功'));
    }

  } catch (e) {
    console.error('[AI客服] 消息处理异常:', e.message);
    return res.json(fail('发送失败'));
  }
});

// ==================== 知识库管理 ====================

router.get('/knowledge', (req, res) => {
  const { keyword } = req.query;
  let where = 'WHERE status=1';
  const params = [];
  if (keyword) {
    where += ' AND (question LIKE ? OR keywords LIKE ?)';
    params.push(`%${keyword}%`, `%${keyword}%`);
  }
  const list = all(`SELECT * FROM ai_knowledge_base ${where} ORDER BY weight DESC LIMIT 50`, params);
  return res.json(success(list));
});

module.exports = router;
