// 微信视频号解析路由（挂载到省胜优铺商城3001端口）
const express = require('express');
const path = require('path');
const fs = require('fs');
const http = require('http');
const { exec } = require('child_process');
const { authAdmin } = require('../middleware/auth');
const router = express.Router();

const TOOL_DIR = path.resolve(__dirname, '..', '..', '..', '..', 'tools', 'video-extractor');
const OUTPUT_DIR = path.join(TOOL_DIR, 'output');
const COOKIE_FILE = path.join(TOOL_DIR, 'yuanbao_cookie.txt');
const EXTRACT_SCRIPT = path.join(TOOL_DIR, 'extract.sh');

// 前端页面
router.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '..', '..', 'public', 'wechat.html'));
});

// 解析API（🔒 仅管理员：该功能含 exec shell 拼接 + 请求外部URL，属命令注入/SSRF面，禁止匿名访问）
router.post('/api/parse', authAdmin, async (req, res) => {
  const shareUrl = req.body.url;
  if (!shareUrl) return res.json({ error: '请提供视频号链接' });

  let cookie;
  try {
    cookie = fs.readFileSync(COOKIE_FILE, 'utf-8').trim().replace(/\n/g, '; ').replace(/; $/, '');
  } catch (e) {
    return res.json({ error: 'Cookie未配置，联系管理员更新' });
  }

  // Step 1: 元宝解析
  const parseResult = await httpPost('https://yuanbao.tencent.com/api/weixin/get_parse_result', {
    headers: {
      'Content-Type': 'application/json', 'Cookie': cookie,
      'Origin': 'https://yuanbao.tencent.com', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
    },
    body: JSON.stringify({ type: 'video_channel_url', url: shareUrl, scene: 1 })
  });
  if (!parseResult) return res.json({ error: '元宝API请求超时，cookie可能已过期' });

  let parseData;
  try { parseData = JSON.parse(parseResult); } catch(e) { return res.json({ error: '解析元宝响应失败' }); }
  if (parseData.code !== 0) return res.json({ error: '解析失败: ' + (parseData.msg || '未知错误') });

  const data = parseData.data;
  const author = data.author || '';
  const desc = (data.desc || '').substring(0, 100);
  const playableUrl = data.playable_url || '';
  const coverUrl = data.cover_url || '';

  const tokenMatch = playableUrl.match(/token=([^&]+)/);
  const eidMatch = playableUrl.match(/eid=([^&]+)/);
  if (!tokenMatch || !eidMatch) return res.json({ error: '无法提取视频参数' });

  const token = decodeURIComponent(tokenMatch[1]);
  const eid = decodeURIComponent(eidMatch[1]);

  // Step 2: 获取视频下载地址
  const feedResult = await httpPost(
    `https://channels.weixin.qq.com/finder-preview/api/feed/get_feed_info?_rid=${Date.now()}`,
    {
      headers: {
        'Content-Type': 'application/json', 'Origin': 'https://channels.weixin.qq.com',
        'Referer': `https://channels.weixin.qq.com/finder-preview/pages/feed?token=${token}&eid=${eid}`,
        'User-Agent': 'Mozilla/5.0'
      },
      body: JSON.stringify({ baseReq: { generalToken: token }, exportId: eid })
    }
  );
  if (!feedResult) return res.json({ error: '获取视频信息超时' });

  let feedData;
  try { feedData = JSON.parse(feedResult); } catch(e) { return res.json({ error: '解析视频信息失败' }); }

  const videoUrl = feedData?.data?.feedInfo?.videoUrl ||
                   feedData?.data?.feedInfo?.h264VideoInfo?.videoUrl || '';
  if (!videoUrl) return res.json({ error: '未找到视频下载地址' });

  // 立即返回视频信息
  res.json({ success: true, author, desc, coverUrl, videoUrl, message: '视频解析成功，后台提取图片中...' });

  // 后台异步下载+提取（0.5秒后开始）
  const videoFile = `/tmp/wechat_video_${Date.now()}.mp4`;
  exec(`sleep 0.5 && wget -q -O "${videoFile}" "${videoUrl}" && bash "${EXTRACT_SCRIPT}" "${videoFile}" --interval 3 --best --format png 2>&1`, { timeout: 120000 }, () => {
    fs.unlink(videoFile, () => {});
  });
});

// 查看最近的输出
router.get('/api/latest', (req, res) => {
  try {
    const dirs = fs.readdirSync(OUTPUT_DIR)
      .filter(f => fs.statSync(path.join(OUTPUT_DIR, f)).isDirectory())
      .sort((a, b) => fs.statSync(path.join(OUTPUT_DIR, b)).mtimeMs - fs.statSync(path.join(OUTPUT_DIR, a)).mtimeMs);

    if (dirs.length === 0) return res.json({ error: '暂无提取记录' });

    const latest = dirs[0];
    const dirPath = path.join(OUTPUT_DIR, latest);
    const files = fs.readdirSync(dirPath).filter(f => f.endsWith('.png') || f.endsWith('.jpg'));
    
    res.json({
      dir: latest,
      frames: files.length,
      galleryUrl: `/wechat-video/output/${latest}/gallery.html`,
      images: files.slice(0, 20)
    });
  } catch(e) {
    res.json({ error: e.message });
  }
});

// 输出静态文件
router.use('/output', express.static(OUTPUT_DIR));

function httpPost(url, opts) {
  return new Promise((resolve) => {
    const u = new URL(url);
    const isHttps = u.protocol === 'https:';
    const mod = isHttps ? require('https') : http;
    const port = u.port || (isHttps ? 443 : 80);
    
    if (opts.body && !opts.headers['Content-Length']) {
      opts.headers['Content-Length'] = Buffer.byteLength(opts.body);
    }
    
    const options = {
      hostname: u.hostname,
      port: port,
      path: u.pathname + u.search,
      method: 'POST',
      headers: opts.headers || {},
      rejectUnauthorized: false
    };
    
    const req = mod.request(options, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve(data));
    });
    req.on('error', (err) => { console.error('httpPost error:', err.message); resolve(null); });
    req.setTimeout(opts.timeout || 15000, () => { req.destroy(); resolve(null); });
    if (opts.body) req.write(opts.body);
    req.end();
  });
}

module.exports = router;
