import { getWaveRawList } from './waveRawStore'

const MAX_CACHE_SIZE = 6

const cache = new Map<string, unknown>()

function dataFingerprint(data: unknown[][] | undefined): string {
    if (!data?.length) return '0'
    const first = data[0]
    const last = data[data.length - 1]
    return `${data.length}:${first?.[0]}:${last?.[0]}`
}

export function buildWaveCacheKey(
    type: 'shu' | 'rms',
    wp: Record<string, any> | undefined,
    value: number,
    isOpen: boolean,
    boxoList: Record<string, any>
): string {
    if (!wp) return ''
    const rawList = wp.waveStoreKey
        ? getWaveRawList(type, wp.waveStoreKey)
        : ((type === 'shu' ? wp.listWaveData : wp.listRmsData) as unknown[][] | undefined)
    const waveFp = dataFingerprint(rawList)
    const boxoFp = boxoList?.startTime ?? boxoList?.lineName ?? boxoList?.equipmentName ?? ''
    return `${type}|${wp.time}|${wp.waveType}|${wp.iphasic}|${value}|${isOpen}|${waveFp}|${boxoFp}`
}

export function getWaveCache<T>(key: string): T | null {
    if (!key || !cache.has(key)) return null
    const value = cache.get(key) as T
    cache.delete(key)
    cache.set(key, value)
    return value
}

export function setWaveCache(key: string, value: unknown): void {
    if (!key) return
    if (cache.has(key)) cache.delete(key)
    cache.set(key, value)
    while (cache.size > MAX_CACHE_SIZE) {
        const oldest = cache.keys().next().value
        if (oldest !== undefined) cache.delete(oldest)
    }
}

export function clearWaveCache(): void {
    cache.clear()
}
