/**
 * LiteMall AI 店铺分析路由（管理后台使用）
 * 
 * 技能：skill_shop_analysis
 * 功能：销售趋势解读、热销/滞销分析、运营建议、日报生成
 * 
 * 权限：管理员
 */

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 { chatWithSkill } = require('../lib/ai-client');
const { isFeatureEnabled } = require('../lib/license');

router.use(authAdmin);

// ==================== 工具函数 ====================

    // NOTE: getSalesTrend 是标准 SQL 聚合查询，SQLite 索引覆盖 created_at，无性能问题

function getSalesTrend(days = 7) {
  return all(`SELECT date(created_at) as d, 
    COUNT(*) as order_count,
    COALESCE(SUM(pay_amount),0) as sales_amount,
    COALESCE(AVG(pay_amount),0) as avg_amount
    FROM orders 
    WHERE status NOT IN ('pending_pay','closed') 
    AND created_at >= date('now','localtime','-${+days} day')
    GROUP BY d ORDER BY d ASC`);
}

function getTopProducts(limit = 10) {
  return all(`SELECT oi.product_id, oi.product_name, oi.image,
    SUM(oi.quantity) as total_qty, SUM(oi.subtotal) as total_amount,
    COUNT(DISTINCT oi.order_id) as order_count
    FROM order_items oi JOIN orders o ON oi.order_id=o.id
    WHERE o.status NOT IN ('pending_pay','closed')
    GROUP BY oi.product_id ORDER BY total_qty DESC LIMIT ?`, [+limit]);
}

function getUserGrowth(days = 7) {
  return all(`SELECT date(created_at) as d, COUNT(*) as new_users 
    FROM users WHERE phone != 'admin' 
    AND created_at >= date('now','localtime','-${+days} day')
    GROUP BY d ORDER BY d ASC`);
}

function getSummaryStats() {
  const today = all(`SELECT 
    COUNT(*) as today_orders,
    COALESCE(SUM(pay_amount),0) as today_sales,
    COUNT(DISTINCT user_id) as today_buyers
    FROM orders WHERE date(created_at)=date('now','localtime')
    AND status NOT IN ('pending_pay','closed')`)[0] || {};

  const total = get("SELECT COUNT(*) as total_orders, COALESCE(SUM(pay_amount),0) as total_sales FROM orders WHERE status NOT IN ('pending_pay','closed')") || {};

  const users = get("SELECT COUNT(*) as total_users FROM users WHERE phone != 'admin'") || {};
  const products = get("SELECT COUNT(*) as total_products FROM products WHERE status=1") || {};

  return { today, total, users, products };
}

// ==================== AI 分析 ====================

/**
 * AI 销售趋势解读
 * POST /api/ai-analysis/sales-insight
 * Body: { days: 7 }
 */
router.post('/sales-insight', async (req, res) => {
  try {
    const { days = 7 } = req.body;
    const stats = getSummaryStats();
    const trend = getSalesTrend(days);

    const dataStr = JSON.stringify({
      days,
      today_orders: stats.today.today_orders || 0,
      today_sales: stats.today.today_sales || 0,
      today_buyers: stats.today.today_buyers || 0,
      total_orders: stats.total.total_orders || 0,
      total_sales: stats.total.total_sales || 0,
      total_users: stats.users.total_users || 0,
      total_products: stats.products.total_products || 0,
      trend: trend.map(t => ({ date: t.d, orders: t.order_count, sales: t.sales_amount })),
    });

    const reply = await chatWithSkill('shop_analysis', [
      { role: 'user', content: `请分析以下店铺销售数据，给出运营洞察和建议：\n\n${dataStr}` }
    ]);

    // 保存分析结果

    return res.json(success({ analysis: reply, data: { stats, trend } }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 热销/滞销分析
 * POST /api/ai-analysis/product-insight
 * Body: { top: 10 }
 */
router.post('/product-insight', async (req, res) => {
  try {
    const { top = 10 } = req.body;
    const topProducts = getTopProducts(top);

    // 获取滞销商品（有库存但销量为0）
    const slowProducts = all(`SELECT id, name, stock, sales FROM products 
      WHERE status=1 AND stock > 0 AND sales = 0 
      ORDER BY stock DESC LIMIT 10`);

    const dataStr = JSON.stringify({
      hot: topProducts.map(p => ({ name: p.product_name, sales: p.total_qty, amount: p.total_amount })),
      slow: slowProducts.map(p => ({ name: p.name, stock: p.stock })),
    });

    const reply = await chatWithSkill('shop_analysis', [
      { role: 'user', content: `请分析以下商品销售数据，给出运营建议：\n\n${dataStr}` }
    ]);

    try {
      run("INSERT INTO ai_analysis_logs(type, days, raw_data, analysis, admin_id) VALUES(?,?,?,?,?)",
        ['product_insight', 30, dataStr.substring(0, 500), reply, req.userId]);
    } catch (e) { /* 静默 */ }

    return res.json(success({ analysis: reply, data: { hot: topProducts, slow: slowProducts } }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 运营日报生成
 * POST /api/ai-analysis/daily-report
 */
router.post('/daily-report', async (req, res) => {
  try {
    const stats = getSummaryStats();
    const trend = getSalesTrend(7);

    const topProducts = getTopProducts(5);
    const userGrowth = getUserGrowth(7);

    const dataStr = JSON.stringify({
      today: {
        orders: stats.today.today_orders || 0,
        sales: parseFloat(stats.today.today_sales || 0).toFixed(2),
        buyers: stats.today.today_buyers || 0,
      },
      total: {
        orders: stats.total.total_orders || 0,
        sales: parseFloat(stats.total.total_sales || 0).toFixed(2),
        users: stats.users.total_users || 0,
        products: stats.products.total_products || 0,
      },
      last_7_days_trend: trend.map(t => ({ date: t.d, orders: t.order_count, sales: t.sales_amount })),
      top_5_products: topProducts.map(p => p.product_name),
      new_users_trend: userGrowth.map(u => ({ date: u.d, count: u.new_users })),
    });

    const reply = await chatWithSkill('shop_analysis', [
      { role: 'user', content: `请为店铺生成一份今日运营日报，包含数据总结和明日行动建议：\n\n${dataStr}` }
    ]);

    try {
      run("INSERT INTO ai_analysis_logs(type, days, raw_data, analysis, admin_id) VALUES(?,?,?,?,?)",
        ['daily_report', 1, dataStr.substring(0, 500), reply, req.userId]);
    } catch (e) { /* 静默 */ }

    return res.json(success({ report: reply, data: stats }));
  } catch (e) {
    return res.json(fail(e.message));
  }
});

/**
 * AI 自由问答（基于店铺数据）
 * POST /api/ai-analysis/ask
 * Body: { question }
 */
router.post('/ask', async (req, res) => {
  try {
    const { question } = req.body;
    if (!question) return res.json(fail('请输入您的问题'));

    // 根据问题类型决定需要加载哪些数据
    const stats = getSummaryStats();
    const trend = getSalesTrend(30);
    const topProducts = getTopProducts(5);
    const userGrowth = getUserGrowth(30);

    const shopData = {
      stats,
      recent_trend: trend.slice(-7),
      top_products: topProducts.slice(0, 5),
      user_growth: userGrowth.slice(-7),
    };

    const reply = await chatWithSkill('shop_analysis', [
      { role: 'user', content: `用户提问：${question}\n\n当前店铺数据：\n${JSON.stringify(shopData, null, 2)}\n\n请基于数据回答用户的问题。` }
    ]);

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

/**
 * 获取分析历史
 * GET /api/ai-analysis/history?type=sales_insight&page=1&pageSize=10
 */
router.get('/history', (req, res) => {
  const { type, page: p = 1, pageSize = 10 } = req.query;
  let where = 'WHERE 1=1';
  const params = [];
  if (type) { where += ' AND type=?'; params.push(type); }
  const list = all(`SELECT * FROM ai_analysis_logs ${where} ORDER BY id DESC LIMIT ? OFFSET ?`,
    [...params, pageSize, (Math.max(1, +p) - 1) * pageSize]);
  return res.json(success(list));
});

module.exports = router;
