import Foundation

/// Offline-first queue: every batch is written to disk first and uploaded by Uploader. Nothing is lost without network;
/// the server ignores duplicates (device, parameter, time).
actor ReadingQueue {
    static let shared = ReadingQueue()
    struct Item: Codable { let id: UUID; let body: Data; let created: Date; let summary: String }
    struct Log: Codable, Identifiable { var id = UUID(); let at: Date; let text: String; let flag: String? }
    private var items: [Item] = []
    private var history: [Log] = []
    private let url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("carepulse-queue.json")
    private let logUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("carepulse-history.json")

    init() {
        try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
        items = (try? JSONDecoder().decode([Item].self, from: Data(contentsOf: url))) ?? []
        history = (try? JSONDecoder().decode([Log].self, from: Data(contentsOf: logUrl))) ?? []
    }
    private func save() {
        try? JSONEncoder().encode(items).write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
        try? JSONEncoder().encode(history).write(to: logUrl, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
    }

    func add(_ batch: [String: Any], summary: String) {
        guard let d = try? JSONSerialization.data(withJSONObject: batch) else { return }
        items.append(Item(id: UUID(), body: d, created: Date(), summary: summary)); save()
    }
    func peek(_ n: Int = 100) -> [Item] { Array(items.prefix(n)) }
    func remove(_ ids: Set<UUID>) { items.removeAll { ids.contains($0.id) }; save() }
    func count() -> Int { items.count }
    func log(_ text: String, flag: String? = nil) { history.insert(Log(at: Date(), text: text, flag: flag), at: 0); history = Array(history.prefix(200)); save() }
    func recent(_ n: Int = 50) -> [Log] { Array(history.prefix(n)) }
}
