import APIClient
import Foundation

final actor ClipPlayCountCache: Sendable {
    private var clipPlayCount: [String: Int] = [:]
    private var accessOrder: [String] = []
    private let maxCacheSize = 500

    func getClipPlayCount(for hookId: String) -> Int? {
        if clipPlayCount[hookId] != nil {
            updateAccessOrder(for: hookId)
        }
        return clipPlayCount[hookId]
    }

    func setClipPlayCount(_ playCount: Int, for hookId: String) {
        clipPlayCount[hookId] = playCount
        updateAccessOrder(for: hookId)
        evictIfNeeded()
    }

    func hydrateFromHooks(_ hooks: [Hook]) {
        for hook in hooks {
            guard let clip = hook.clip else { continue }
            clipPlayCount[hook.id] = clip.playCount
            updateAccessOrder(for: hook.id)
        }
        evictIfNeeded()
    }

    func removeHook(_ hookId: String) {
        clipPlayCount.removeValue(forKey: hookId)
        accessOrder.removeAll { $0 == hookId }
    }

    private func updateAccessOrder(for hookId: String) {
        accessOrder.removeAll { $0 == hookId }
        accessOrder.append(hookId)
    }

    private func evictIfNeeded() {
        while clipPlayCount.count > maxCacheSize {
            guard let leastUsed = accessOrder.first else { break }
            clipPlayCount.removeValue(forKey: leastUsed)
            accessOrder.removeFirst()
        }
    }
}
