import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const dataDir = path.resolve(__dirname, '../data')
const statusFile = path.join(dataDir, 'capture-status.json')

function ensureDir() {
    if (!fs.existsSync(dataDir)) {
        fs.mkdirSync(dataDir, { recursive: true })
    }
}

export function ensureDataFiles() {
    ensureDir()

    if (!fs.existsSync(statusFile)) {
        fs.writeFileSync(
            statusFile,
            JSON.stringify(
                {
                    running: false,
                    lastMessage: '未启动采集',
                    updatedAt: null
                },
                null,
                2
            ),
            'utf-8'
        )
    }
}

export function getYearFile(year) {
    ensureDir()
    return path.join(dataDir, `${year}.json`)
}

export function readYearData(year) {
    ensureDir()
    const file = getYearFile(year)

    if (!fs.existsSync(file)) {
        return {
            year,
            updatedAt: null,
            items: []
        }
    }

    return JSON.parse(fs.readFileSync(file, 'utf-8'))
}

export function writeYearData(year, data) {
    ensureDir()
    const file = getYearFile(year)
    fs.writeFileSync(file, JSON.stringify(data, null, 2), 'utf-8')
}

export function getAllYearFiles() {
    ensureDir()

    return fs
        .readdirSync(dataDir)
        .filter((file) => /^\d{4}\.json$/.test(file))
        .sort()
}

export function readAllYearsData() {
    ensureDir()

    const files = getAllYearFiles()
    const allItems = []
    const years = []

    for (const file of files) {
        const year = Number(file.replace('.json', ''))
        const data = readYearData(year)

        years.push(year)

        if (Array.isArray(data.items)) {
            allItems.push(...data.items)
        }
    }

    allItems.sort((a, b) => (b.releasedAt || 0) - (a.releasedAt || 0))

    return {
        updatedAt: new Date().toISOString(),
        name: '七十二家房客',
        coverUrl: '',
        displayType: 0,
        years,
        items: allItems
    }
}

export function readStatus() {
    ensureDataFiles()
    return JSON.parse(fs.readFileSync(statusFile, 'utf-8'))
}

export function writeStatus(status) {
    ensureDataFiles()
    fs.writeFileSync(statusFile, JSON.stringify(status, null, 2), 'utf-8')
}
