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

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

const dropsSourceDir = path.join(__dirname, '../drops')
const dropsPublicDir = path.join(__dirname, '../app/public/drops')
const outputPath = path.join(__dirname, '../app/public/manifest.json')

/**
 * Get all published drops by reading their meta.json files from the source drops directory
 */
const getPublishedDrops = () => {
    const drops = fs
        .readdirSync(dropsSourceDir, { withFileTypes: true })
        .filter((dirent) => dirent.isDirectory())
        .map((dirent) => dirent.name)

    const publishedDrops = drops.filter((dropName) => {
        const metaPath = path.join(dropsSourceDir, dropName, 'public/meta.json')

        if (!fs.existsSync(metaPath)) {
            console.warn(
                `Warning: meta.json not found for drop "${dropName}", skipping...`,
            )
            return false
        }

        try {
            const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'))
            return meta.published === true
        } catch (err) {
            console.error(
                `Error reading meta.json for drop "${dropName}":`,
                err.message,
            )
            return false
        }
    })

    return publishedDrops
}

const publishedDrops = getPublishedDrops()

// Only include drops that are both published and actually built (exist in public/drops)
const builtPublishedDrops = publishedDrops.filter((dropName) => {
    const dropDir = path.join(dropsPublicDir, dropName)
    return fs.existsSync(dropDir)
})

/**
 * Sort drops by date (newest first)
 */
const sortDropsByDate = (dropNames) => {
    const dropsWithDates = dropNames.map((dropName) => {
        const metaPath = path.join(dropsPublicDir, dropName, 'meta.json')
        let date = null

        if (fs.existsSync(metaPath)) {
            try {
                const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'))
                date = meta.date || null
            } catch (err) {
                console.warn(
                    `Warning: Could not read date from built meta.json for "${dropName}"`,
                )
            }
        }

        return { name: dropName, date }
    })

    // Sort by date descending (newest first), put drops without dates at the end
    dropsWithDates.sort((a, b) => {
        if (!a.date && !b.date) return 0
        if (!a.date) return 1
        if (!b.date) return -1
        return new Date(b.date) - new Date(a.date)
    })

    return dropsWithDates.map((drop) => drop.name)
}

const sortedDrops = sortDropsByDate(builtPublishedDrops)

fs.writeFileSync(outputPath, JSON.stringify(sortedDrops, null, 2))

console.log(
    `Manifest created with ${sortedDrops.length} published drop(s) (sorted by date):`,
    sortedDrops,
)
