import fs from 'node:fs'
import path from 'node:path'
import { 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 result = await seedConfigAvatarFramesFromCatalog(db)
    const configCount = await db.get<{ c: number }>('SELECT COUNT(*) AS c FROM config_avatar_frames')
    const orphanUser = await db.get<{ c: number }>(
        `SELECT COUNT(*) AS c FROM user_avatar_frames uaf
         LEFT JOIN config_avatar_frames af ON af.item_id = uaf.frame_id
         WHERE af.item_id IS NULL`
    )

    await db.close()

    console.log(`Backed up user_avatar_frames: ${result.backedUp}`)
    console.log(`Synced config_avatar_frames: ${result.inserted} (total ${configCount?.c ?? 0})`)
    console.log(`Restored user_avatar_frames: ${result.restored} (skipped ${result.skipped})`)
    console.log(`Orphan user_avatar_frames: ${orphanUser?.c ?? 0}`)
}

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