import Foundation
import UIKit
import UserNotifications

/// Uploads queued batches (max 100 per call), sends a heartbeat and refreshes config.
enum Uploader {
    @discardableResult
    static func run() async -> Bool {
        let s = Settings.shared
        guard let server = s.server, let token = s.token else { return false }
        let api = Api(server: server, token: token), q = ReadingQueue.shared
        do {
            while true {
                let items = await q.peek(100)
                if items.isEmpty { break }
                let batches = items.compactMap { try? JSONSerialization.jsonObject(with: $0.body) as? [String: Any] }
                let res = try await api.readings(batches)
                var done = Set<UUID>()
                for r in (res["results"] as? [[String: Any]]) ?? [] {
                    guard let i = r["index"] as? Int, i < items.count else { continue }
                    done.insert(items[i].id)   // ok or permanent rejection: do not retry forever
                    for a in (r["alerts"] as? [[String: Any]]) ?? [] { await notify(a) }
                    if (r["ok"] as? Bool) != true { await q.log("Not accepted: \(r["error"] as? String ?? "")", flag: "error") }
                    else if (r["patient_assigned"] as? Bool) == false { await q.log("Saved – hospital staff will confirm which patient it belongs to", flag: "pending") }
                }
                if done.isEmpty { return false }
                await q.remove(done)
            }
            let (battery, info) = await MainActor.run { () -> (Int, String) in
                UIDevice.current.isBatteryMonitoringEnabled = true
                return (Int(max(0, UIDevice.current.batteryLevel) * 100), "iOS \(UIDevice.current.systemVersion) · \(UIDevice.current.model)")
            }
            try await api.heartbeat(["battery": battery, "app_version": "ios-3.0.0", "device_info": info])
            let cfg = try await api.config()
            await MainActor.run { s.configJSON = try? JSONSerialization.data(withJSONObject: cfg) }
            return true
        } catch let e as ApiError where e.status == 401 {
            await q.log("This phone was unpaired by the hospital. Pair again.", flag: "error"); return false
        } catch {
            return false   // offline: try again later
        }
    }

    private static func notify(_ a: [String: Any]) async {
        let c = UNMutableNotificationContent()
        c.title = (a["severity"] as? String) == "critical" ? "Reading needs attention" : "Reading outside your range"
        c.body = (a["message"] as? String ?? "") + " Your care team has been informed."
        try? await UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: UUID().uuidString, content: c, trigger: nil))
    }
}
