const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = 3000;

app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));

const ACTIVITY_URL = 'https://www.szhdy.com/activities/default.html?method=activity&id=9';
const REQUEST_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
};

// 存储 Cookie
let cachedCookies = '';
let cookieExpiry = 0;

// 从 set-cookie 响应头提取 Cookie
function extractCookies(response) {
    const setCookieHeaders = response.headers.getSetCookie?.() || [];
    const cookies = setCookieHeaders.map(c => c.split(';')[0]).join('; ');
    return cookies;
}

// 获取有效 Cookie（过期或为空时重新获取）
async function getValidCookies() {
    if (cachedCookies && Date.now() < cookieExpiry) {
        return cachedCookies;
    }

    console.log('[Cookie] 正在获取新的 Cookie...');
    const response = await fetch(ACTIVITY_URL, { headers: REQUEST_HEADERS, redirect: 'manual' });
    cachedCookies = extractCookies(response);
    // Cookie 有效期设为 1 小时（服务器 max-age=86400，保守取 1 小时）
    cookieExpiry = Date.now() + 3600 * 1000;
    console.log('[Cookie] 获取成功:', cachedCookies);
    return cachedCookies;
}

app.get('/api/activity', async (req, res) => {
    try {
        const cookies = await getValidCookies();
        const response = await fetch(ACTIVITY_URL, {
            headers: {
                ...REQUEST_HEADERS,
                'Cookie': cookies,
            }
        });

        const html = await response.text();

        // 如果返回内容过短，可能 Cookie 失效，清除缓存并重试一次
        if (html.length < 1000) {
            console.log('[Cookie] 响应内容过短，尝试刷新 Cookie 重试...');
            cachedCookies = '';
            cookieExpiry = 0;
            const newCookies = await getValidCookies();
            const retryResponse = await fetch(ACTIVITY_URL, {
                headers: {
                    ...REQUEST_HEADERS,
                    'Cookie': newCookies,
                }
            });
            const retryHtml = await retryResponse.text();
            // 更新重试后的 Cookie
            const retryCookies = extractCookies(retryResponse);
            if (retryCookies) {
                cachedCookies = retryCookies;
                cookieExpiry = Date.now() + 3600 * 1000;
            }
            return res.json({ success: true, html: retryHtml });
        }

        // 更新响应中的新 Cookie
        const newCookies = extractCookies(response);
        if (newCookies) {
            cachedCookies = newCookies;
            cookieExpiry = Date.now() + 3600 * 1000;
        }

        res.json({ success: true, html });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
});

app.listen(PORT, () => {
    console.log(`活动监控服务已启动: http://localhost:${PORT}`);
});
