/**
 * 飞速直播 (fszb30.com) 流 URL 提取
 * 用法: node fszb_stream.js <room_id> [sport_id] [cookie_string]
 * 输出 JSON: {"streams":[{"url":"...","quality":"高清/标清/蓝光","label":"高清(gq)"}]}
 */

const { chromium } = require('playwright-core');
const fs = require('fs');
const path = require('path');

const AUTH_FILE = path.join(__dirname, '..', 'auth', 'fszb_state.json');

// 画质关键词 → 标签映射
const QUALITY_MAP = [
    { keys: ['lq', '_lan', 'bluray', '1080', 'blue', '_cqz'], label: '蓝光', prio: 30 },
    { keys: ['gq', 'high', 'hd', '720', '_cq', 'chaoq'], label: '高清', prio: 20 },
    { keys: ['bq', 'sd', 'standard', '480', '360', 'low', 'liuch'], label: '标清', prio: 10 },
];

function guessQuality(url) {
    const lower = url.toLowerCase();
    for (const q of QUALITY_MAP) {
        for (const k of q.keys) {
            if (lower.includes(k)) return { quality: q.label, prio: q.prio, key: k };
        }
    }
    return { quality: '默认', prio: 5, key: '' };
}

(async () => {
    const roomId = process.argv[2] || '288395848';
    const sportId = process.argv[3] || '1';
    const cookieStr = process.argv[4] || '';
    const url = `https://www.fszb30.com/broadcast/details?room_id=${roomId}&sport_id=${sportId}`;

    const browser = await chromium.launch({ headless: true, channel: 'chrome' });

    let storageState = null;
    if (fs.existsSync(AUTH_FILE)) {
        try { storageState = JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8')); } catch (e) {}
    }
    const contextOpts = {};
    if (storageState && storageState.cookies && storageState.cookies.length > 0) {
        contextOpts.storageState = AUTH_FILE;
    }
    const context = await browser.newContext(contextOpts);

    if (cookieStr) {
        const cookies = cookieStr.split(';').map(c => {
            const [name, ...rest] = c.trim().split('=');
            return { name: name.trim(), value: rest.join('=').trim(), domain: '.fszb30.com', path: '/' };
        }).filter(c => c.name);
        if (cookies.length > 0) try { await context.addCookies(cookies); } catch (e) {}
    }
    const page = await context.newPage();

    // 收集所有流 URL（不去重，先全抓）
    const streamUrls = new Set();

    page.on('request', req => {
        const rurl = req.url();
        if (/\.(flv|m3u8)(\?|$)/i.test(rurl) && !/\.(js|css|woff|png|jpg|gif)/i.test(rurl)) {
            streamUrls.add(rurl);
        }
    });
    page.on('response', async resp => {
        const rurl = resp.url();
        if (/\.(flv|m3u8)(\?|$)/i.test(rurl) && !/\.(js|css|woff|png|jpg|gif)/i.test(rurl)) {
            streamUrls.add(rurl);
        }
    });

    try {
        await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 });

        // 从 DOM 找 video src
        const srcFromDOM = await page.evaluate(() => {
            const v = document.querySelector('video');
            if (v && (v.src || v.currentSrc)) return v.src || v.currentSrc;
            const s = document.querySelector('video source');
            if (s && s.src) return s.src;
            return null;
        });
        if (srcFromDOM) streamUrls.add(srcFromDOM);

        // 点击播放按钮
        const clickTargets = [
            'button.play', '.play-btn', '[class*="play"]', 'video',
            '.prism-player', '#player', '.vjs-big-play-button',
            '[class*="live"]', '[class*="player"]', '.start-play'
        ];
        for (const sel of clickTargets) {
            try {
                const els = await page.$$(sel);
                for (const el of els) {
                    try { await el.click({ timeout: 1000 }); await page.waitForTimeout(600); } catch (e) {}
                }
            } catch (e) {}
        }

        // 尝试点击画质切换按钮，触发加载不同画质的流
        // 更全面的画质选择器
        const qualitySelectors = [
            '.quality-item', '.definition-item', '[class*="quality"]',
            '[class*="definition"]', '[class*="resolution"]', '[class*="画质"]',
            '[class*="清晰度"]', '[class*="hz"]', '.rate-item', '[class*="rate"]',
            '[class*="clarity"]', '[data-quality]', '[data-definition]',
            'li[class*="q"]', 'span[class*="q"]', '.quality-btn'
        ];

        // 收集所有候选画质元素
        const qEls = [];
        for (const sel of qualitySelectors) {
            try {
                const els = await page.$$(sel);
                for (const el of els) {
                    try {
                        const text = (await el.textContent()) || '';
                        const isVis = await el.isVisible();
                        if (isVis && text.trim().length > 0 && text.trim().length < 20) {
                            qEls.push(el);
                        }
                    } catch (e) {}
                }
            } catch (e) {}
        }

        // 去重后逐个点击
        const clicked = new Set();
        for (const el of qEls) {
            try {
                const text = (await el.textContent()).trim();
                if (!clicked.has(text)) {
                    clicked.add(text);
                    await el.click({ timeout: 1000 });
                    await page.waitForTimeout(1500);
                }
            } catch (e) {}
        }

        // 额外：用 keyboard 模拟点击画质切换快捷键（部分播放器支持）
        // 通过 evaluate 查找并调用页面里的切换函数
        try {
            await page.evaluate(() => {
                // 尝试触发播放器的画质切换 API
                const player = document.querySelector('video')?.__player;
                if (!player) return;
                const qualities = player.getQualities?.() || [];
                qualities.forEach(q => { try { player.setQuality?.(q); } catch(e) {} });
            });
        } catch (e) {}

        // 等待收集更多流 URL
        for (let i = 0; i < 20; i++) {
            await page.waitForTimeout(1000);
        }
    } catch (e) {
        // timeout ok
    }

    // 处理收集到的流 URL
    const streams = [];
    const seen = new Set();
    for (const u of streamUrls) {
        // 去重（忽略 token 等参数差异，用路径部分去重）
        const base = u.replace(/[?&](txSecret|txTime|token|expires|device|platform|sign|t|_t)=[^&]*/g, '');
        if (seen.has(base)) continue;
        seen.add(base);
        const gq = guessQuality(u);
        streams.push({
            url: u,
            quality: gq.quality,
            label: gq.quality + (gq.key ? ' (' + gq.key + ')' : ''),
            priority: gq.prio
        });
    }

    // 按画质优先级降序
    streams.sort((a, b) => b.priority - a.priority);

    // 删除内部 priority 字段
    const result = streams.map(({ url, quality, label }) => ({ url, quality, label }));

    if (result.length > 0) {
        console.log(JSON.stringify({ streams: result }));
    } else {
        try {
            const debug = await page.evaluate(() => ({
                title: document.title,
                hasVideo: !!document.querySelector('video'),
                videoSrc: document.querySelector('video')?.src || null,
                bodyText: document.body?.innerText?.substring(0, 200) || ''
            }));
            console.error('DEBUG:', JSON.stringify(debug));
        } catch (e) {}
        console.error('ERROR: 未能获取 FLV 流地址');
        process.exit(1);
    }

    await browser.close();
})();
