import fs from 'node:fs'
import path from 'node:path'
import { open } from 'sqlite'
import sqlite3 from 'sqlite3'
import { resolveAvatarFrameAssetUrl } from '../lib/avatarFrames/resolveUrl'

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 open({ filename: dbPath, driver: sqlite3.Database })
    const rows = await db.all<{ item_id: string; img_url: string }[]>(
        'SELECT item_id, img_url FROM config_avatar_frames'
    )

    let updated = 0
    await db.exec('BEGIN')
    try {
        const stmt = await db.prepare(
            'UPDATE config_avatar_frames SET img_url = ? WHERE item_id = ?'
        )
        for (const row of rows) {
            const next = resolveAvatarFrameAssetUrl(row.img_url)
            if (next && next !== row.img_url) {
                await stmt.run(next, row.item_id)
                updated++
            }
        }
        await stmt.finalize()
        await db.exec('COMMIT')
    } catch (e) {
        await db.exec('ROLLBACK')
        throw e
    }

    await db.close()
    console.log(`Normalized ${updated} / ${rows.length} config_avatar_frames img_url values`)
}

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