import Foundation

actor WatchHistoryService {
    nonisolated(unsafe) static let shared = WatchHistoryService()

    private let storageService = StorageService.shared
    private let historyKey = "watchHistory"
    private let maxEntries = 50

    private init() {}

    func saveEntry(_ entry: WatchHistoryEntry) async {
        var history = await loadHistory()

        // Remove existing entry for same item if exists
        history.removeAll { $0.id == entry.id }

        // Only add if not completed (>95% watched)
        if !entry.isCompleted {
            history.insert(entry, at: 0)
        }

        // Limit to max entries
        if history.count > maxEntries {
            history = Array(history.prefix(maxEntries))
        }

        do {
            try await storageService.savePreference(history, forKey: historyKey)
        } catch {
            // Silent failure - watch history is non-critical
        }
    }

    func loadHistory() async -> [WatchHistoryEntry] {
        do {
            let history: [WatchHistoryEntry]? = try await storageService.loadPreference(forKey: historyKey)
            return history?.sorted { $0.watchedAt > $1.watchedAt } ?? []
        } catch {
            return []
        }
    }

    func removeEntry(id: String) async {
        var history = await loadHistory()
        history.removeAll { $0.id == id }

        do {
            try await storageService.savePreference(history, forKey: historyKey)
        } catch {
            // Silent failure
        }
    }

    func clearHistory() async {
        await storageService.removePreference(forKey: historyKey)
    }

    func getEntry(forId id: String) async -> WatchHistoryEntry? {
        let history = await loadHistory()
        return history.first { $0.id == id }
    }
}
