import { Router } from 'express';
import { query } from 'express-validator';
import { authenticate } from '../middleware/auth.js';
import { asyncHandler } from '../middleware/error.js';
import { validateRequest } from '../middleware/validate.js';

const router = Router();

router.use(authenticate);

// 在 Node 中声明全局 fetch
// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare const fetch: any;

/**
 * 调用本地 Python 统计服务的工具函数
 * 默认地址: http://localhost:5005
 */
async function callPythonApi(pathname: string, params: Record<string, string | number | undefined>) {
  const base = process.env.PYTHON_API_URL || 'http://localhost:5005';
  const url = new URL(base);
  url.pathname = pathname.startsWith('/') ? pathname : `/${pathname}`;

  const search = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      search.append(key, String(value));
    }
  });
  url.search = search.toString();

  try {
    const resp = await fetch(url.toString(), { method: 'GET' });
    
    if (!resp.ok) {
      let errorData: any;
      try {
        errorData = await resp.json();
      } catch {
        const text = await resp.text();
        errorData = {
          success: false,
          error: `Python API 返回错误 (${resp.status}): ${text.substring(0, 500)}`,
        };
      }
      throw new Error(errorData.error || `Python API 返回错误: ${resp.status} ${resp.statusText}`);
    }

    const contentType = resp.headers.get('content-type') || '';
    if (!contentType.includes('application/json')) {
      const text = await resp.text();
      throw new Error(`Python API 返回非 JSON 响应: ${text.substring(0, 500)}`);
    }

    const json = await resp.json();
    return json;
  } catch (error: any) {
    if (error.name === 'TypeError' && error.message.includes('fetch')) {
      throw new Error(`无法连接 Python API (${base}): ${error.message}`);
    }
    throw error;
  }
}

/**
 * GET /api/dashboard/trend
 * 获取数据趋势（通过 Node 转发到 Python API）
 * 按平台分组返回，每个平台一条曲线
 * 
 * 查询参数:
 *   - days: 天数（默认30天）
 *   - account_id: 账号ID（可选，不填则查询所有平台）
 * 
 * 返回:
 * {
 *   success: true,
 *   data: {
 *     dates: ["01-01", "01-02", ...],
 *     platforms: [
 *       {
 *         platform: "xiaohongshu",
 *         platformName: "小红书",
 *         fansIncrease: [10, 20, ...],
 *         views: [100, 200, ...],
 *         likes: [50, 60, ...],
 *         comments: [5, 6, ...]
 *       },
 *       ...
 *     ]
 *   }
 * }
 */
router.get(
  '/trend',
  [
    query('days').optional().isInt({ min: 1, max: 30 }).withMessage('days 必须是 1-30 之间的整数'),
    query('account_id').optional().isInt().withMessage('account_id 必须是整数'),
    validateRequest,
  ],
  asyncHandler(async (req, res) => {
    const days = req.query.days ? parseInt(req.query.days as string) : 30;
    const accountId = req.query.account_id ? parseInt(req.query.account_id as string) : undefined;

    try {
      const pythonResult = await callPythonApi('/work_day_statistics/trend', {
        user_id: req.user!.userId,
        days,
        account_id: accountId,
      });

      if (!pythonResult || pythonResult.success === false) {
        return res.status(500).json({
          success: false,
          error: pythonResult?.error || '获取数据趋势失败',
          message: pythonResult?.error || '获取数据趋势失败',
        });
      }

      return res.json({ success: true, data: pythonResult.data });
    } catch (error: any) {
      console.error('[dashboard/trend] 调用 Python API 失败:', error);
      return res.status(500).json({
        success: false,
        error: error.message || '调用 Python API 失败',
        message: error.message || '调用 Python API 失败',
      });
    }
  })
);

export default router;
