import path from 'path'
import fs from 'fs'
import type { AvatarFrameCatalogItem, AvatarFrameCatalogJson } from './types'
import { resolveAvatarFrameAssetUrl } from './resolveUrl'

export const AVATAR_FRAME_CATALOG_PATH = path.join(
    process.cwd(),
    'public',
    'lotties',
    'ring',
    'item.json'
)

/** 舊版 item_id：country:ringId */
export function buildLegacyAvatarFrameItemId(country: string, ringId: number | string): string {
    return `${String(country).trim().toUpperCase()}:${String(ringId).trim()}`
}

/** config_avatar_frames.item_id 使用 item.json 的 ringHashId */
export function buildAvatarFrameItemId(item: Pick<AvatarFrameCatalogItem, 'ringHashId'>): string {
    return String(item.ringHashId).trim()
}

export function parseAvatarFrameCatalog(raw: AvatarFrameCatalogJson): AvatarFrameCatalogItem[] {
    const img = Array.isArray(raw.IMG) ? raw.IMG : []
    const lottie = Array.isArray(raw.LOTTIE) ? raw.LOTTIE : []
    return [...img, ...lottie].filter(
        (item) =>
            item &&
            item.ringId != null &&
            String(item.ringHashId || '').trim() &&
            String(item.url || '').trim()
    )
}

export function readAvatarFrameCatalogFromDisk(
    catalogPath: string = AVATAR_FRAME_CATALOG_PATH
): AvatarFrameCatalogItem[] {
    if (!fs.existsSync(catalogPath)) return []
    const raw = JSON.parse(fs.readFileSync(catalogPath, 'utf8')) as AvatarFrameCatalogJson
    return parseAvatarFrameCatalog(raw)
}

/** 舊 item_id → ringHashId，供資料遷移 */
export function buildAvatarFrameIdMigrationMap(
    items: AvatarFrameCatalogItem[] = readAvatarFrameCatalogFromDisk()
): Map<string, string> {
    const map = new Map<string, string>()
    for (const item of items) {
        const hashId = buildAvatarFrameItemId(item)
        map.set(hashId, hashId)
        map.set(String(item.ringId), hashId)
        const country = String(item.country || '').trim()
        if (country) {
            map.set(buildLegacyAvatarFrameItemId(country, item.ringId), hashId)
        }
    }
    return map
}

export function catalogItemToDbType(type: string): 'IMG' | 'LOTTERY' {
    const upper = String(type || '').trim().toUpperCase()
    return upper === 'LOTTIE' || upper === 'LOTTERY' ? 'LOTTERY' : 'IMG'
}

/** 匯入 DB 前正規化 item.json 的 url */
export function normalizeCatalogItemUrl(url: string): string {
    return resolveAvatarFrameAssetUrl(url)
}

export function normalizeCatalogItemTag(tag: string | null | undefined): string {
    return String(tag ?? '').trim()
}

export function normalizeCatalogItemName(
    item: Pick<AvatarFrameCatalogItem, 'name' | 'ringHashId'>
): string {
    const name = String(item.name ?? '').trim()
    return name || buildAvatarFrameItemId(item)
}
