import fs from 'node:fs'
import path from 'node:path'
import {
    grantMissingCatalogFramesToAllUsers,
    seedConfigAvatarFramesFromCatalog,
} from '../server/avatarFrames/seedConfigAvatarFrames'
import { openSqliteGpLiveDb } from '../server/sqliteGpLiveDb'

const DEFAULT_DB_PATH = path.join(process.cwd(), 'data', 'gp-live.sqlite')

async function main() {
    const dbPath = process.env.GP_LIVE_DB_PATH?.trim() || DEFAULT_DB_PATH
    if (!fs.existsSync(dbPath)) {
        console.error(`Database not found: ${dbPath}`)
        process.exit(1)
    }

    const db = await openSqliteGpLiveDb(dbPath)
    await db.exec(`PRAGMA foreign_keys = ON;`)

    const hasTable = await db.get<{ name: string }>(
        `SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'config_avatar_frames' LIMIT 1`
    )
    if (!hasTable?.name) {
        console.error('config_avatar_frames table missing — start the app once to run migrations.')
        process.exit(1)
    }

    const result = await seedConfigAvatarFramesFromCatalog(db)
    const grant = await grantMissingCatalogFramesToAllUsers(db)
    const configCount = await db.get<{ c: number }>('SELECT COUNT(*) AS c FROM config_avatar_frames')
    const userFrameCount = await db.get<{ c: number }>(
        'SELECT COUNT(*) AS c FROM user_avatar_frames'
    )
    const userCount = await db.get<{ c: number }>('SELECT COUNT(*) AS c FROM users')
    await db.close()
    console.log(
        `Synced ${result.inserted} config items (total ${configCount?.c ?? 0}); user frames backed up ${result.backedUp}, restored ${result.restored}, skipped ${result.skipped}`
    )
    console.log(
        `Granted missing user_avatar_frames: ${grant.added} new rows (total ${userFrameCount?.c ?? 0} across ${userCount?.c ?? 0} users)`
    )
}

main().catch((e) => {
    console.error(e)
    process.exit(1)
})
