import type { AvatarFramePayload } from '@/lib/avatarFrames/types'

/** 頭像框靜態檔根目錄（對應 public/lotties/ring） */
const RING_PUBLIC_BASE = '/lotties/ring'

/** 依資源路徑判斷 IMG / LOTTIE（API 列表不回傳 type 時使用） */
export function inferAvatarFrameTypeFromImage(image: string): AvatarFramePayload['type'] {
    const path = String(image ?? '').toLowerCase()
    if (path.includes('/lottie/') || path.endsWith('.json')) return 'LOTTIE'
    return 'IMG'
}

export function toAvatarFramePayload(
    item: Pick<AvatarFramePayload, 'id' | 'image'> & Partial<Pick<AvatarFramePayload, 'type'>>
): AvatarFramePayload {
    return {
        id: item.id,
        image: item.image,
        type: item.type ?? inferAvatarFrameTypeFromImage(item.image),
    }
}

/**
 * 將 DB / item.json 的相對路徑轉成可從網站根目錄載入的絕對路徑。
 *
 * 例：
 * - `IMG/foo.png` → `/lotties/ring/IMG/foo.png`
 * - `/IMG/foo.png` → `/lotties/ring/IMG/foo.png`
 * - `/lotties/IMG/foo.png` → `/lotties/ring/IMG/foo.png`（實體檔在 ring/IMG）
 * - `LOTTIE/bar.json` → `/lotties/ring/LOTTIE/bar.json`
 */
export function resolveAvatarFrameAssetUrl(url: string | null | undefined): string {
    const raw = String(url ?? '').trim()
    if (!raw) return ''

    if (/^https?:\/\//i.test(raw) || raw.startsWith('//')) {
        return raw
    }

    let path = raw.replace(/\\/g, '/').replace(/^\/+/, '')

    // 已是完整 public 路徑
    if (path.startsWith('lotties/ring/')) {
        return `/${path}`
    }
    if (path.startsWith('lotties/IMG/') || path.startsWith('lotties/LOTTIE/')) {
        const rest = path.slice('lotties/'.length)
        return `${RING_PUBLIC_BASE}/${rest}`
    }

    if (path.startsWith('IMG/') || path.startsWith('LOTTIE/')) {
        return `${RING_PUBLIC_BASE}/${path}`
    }

    if (path.startsWith('ring/IMG/') || path.startsWith('ring/LOTTIE/')) {
        return `/lotties/${path}`
    }

    return raw.startsWith('/') ? raw : `/${raw}`
}
