import express from 'express'
import cors from 'cors'
import axios from 'axios'

const app = express()
app.use(cors())

const beginScoreMap = {
    1: 0,
    2: 1765202160000,
    3: 1764338100000,
    4: 1763561820000,
    5: 1762962000000,
    6: 1762352220000,
    7: 1761746220000,
    8: 1761056280000,
    9: 1740315600000,
    10: 1738414800000,
    11: 1736514000000,
    12: 1734526800000,
    13: 1732714295000,
    14: 1730986358000,
    15: 1729171974000,
    16: 1727442000000,
    17: 1725713999999,
    18: 1723899600000,
    19: 1721998800000,
    20: 1720186339000,
    21: 1718371929000,
    22: 1716641999999,
    23: 1714827600000,
    24: 1713099599999,
    25: 1711372007000,
    26: 1709559052000
}

function buildHeaders() {
    return {
        Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        Origin: 'https://www1.gdtv.cn',
        Referer: 'https://www1.gdtv.cn/',
        'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36',
        'x-itouchtv-ca-key': '89541943007407288657755311868534',
        'x-itouchtv-ca-signature': 'UPNSWKuT1dzRU9WYvdgChNmjU0FdmwSPmwxnmahc+Bo=',
        'x-itouchtv-ca-timestamp': '1773166348175',
        'x-itouchtv-client': 'WEB_PC',
        'x-itouchtv-device-id': 'WEB_c5bf71d0-1c9c-11f1-9b47-2fe652348943'
    }
}

app.get('/api/qishier', async (req, res) => {
    const page = Number(req.query.page || 26)
    const pageSize = Number(req.query.pageSize || 40)
    const beginScore = beginScoreMap[page]

    try {
        if (beginScore === undefined) {
            return res.status(400).json({
                message: `第 ${page} 页缺少 beginScore`
            })
        }

        const response = await axios.get(
            'https://gdtv-api.gdtv.cn/api/tvColumn/v1/news',
            {
                params: {
                    pageSize,
                    currentPage: page,
                    searchByTime: false,
                    tvColumnPk: 768,
                    beginScore
                },
                headers: buildHeaders(),
                timeout: 15000
            }
        )

        res.json(response.data)
    } catch (error) {
        console.error('分页请求失败:', error?.response?.status, error?.response?.data || error.message)
        res.status(error?.response?.status || 500).json({
            message: '分页请求失败',
            status: error?.response?.status || 500,
            data: error?.response?.data || null
        })
    }
})

app.listen(3000, () => {
    console.log('代理服务已启动: http://localhost:3000')
})
