import Foundation
import HealthKit

/// Reads the data types the patient allows from Apple Health (Apple Watch, CGM apps that write glucose, smart scales …)
/// using anchored queries, so each sample is sent once. Background delivery wakes the app when new data arrives.
/// Heart rate is thinned to one value per 15 minutes; steps and active energy are daily totals; sleep is hours per night.
final class HealthKitSync {
    static let shared = HealthKitSync()
    let store = HKHealthStore()

    private let quantity: [(HKQuantityTypeIdentifier, String, HKUnit, String?)] = [
        (.bloodPressureSystolic, "bp_sys", .millimeterOfMercury(), nil), (.bloodPressureDiastolic, "bp_dia", .millimeterOfMercury(), nil),
        (.oxygenSaturation, "spo2", .percent(), nil), (.bloodGlucose, "glucose", HKUnit(from: "mg/dL"), "mg/dL"),
        (.bodyMass, "weight", .gramUnit(with: .kilo), "kg"), (.bodyTemperature, "temp", .degreeCelsius(), "Cel"),
        (.respiratoryRate, "rr", HKUnit.count().unitDivided(by: .minute()), nil), (.restingHeartRate, "resting_hr", HKUnit.count().unitDivided(by: .minute()), nil),
        (.heartRateVariabilitySDNN, "hrv", .secondUnit(with: .milli), nil), (.heartRate, "hr", HKUnit.count().unitDivided(by: .minute()), nil),
    ]
    private var readTypes: Set<HKObjectType> {
        var s = Set<HKObjectType>(quantity.compactMap { HKObjectType.quantityType(forIdentifier: $0.0) })
        s.insert(HKObjectType.quantityType(forIdentifier: .stepCount)!); s.insert(HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!)
        s.insert(HKObjectType.categoryType(forIdentifier: .sleepAnalysis)!)
        return s
    }

    var available: Bool { HKHealthStore.isHealthDataAvailable() }

    func requestAccess() async throws {
        try await store.requestAuthorization(toShare: [], read: readTypes)
        for t in readTypes { try? await store.enableBackgroundDelivery(for: t, frequency: .hourly) }
    }

    /// Observer queries: Apple Health wakes the app when new samples arrive; we sync and upload.
    func startObserving() {
        for t in readTypes.compactMap({ $0 as? HKSampleType }) {
            store.execute(HKObserverQuery(sampleType: t, predicate: nil) { _, done, _ in
                Task { if await self.sync() > 0 { await Uploader.run() }; done() }
            })
        }
    }

    private func anchored(_ type: HKSampleType, key: String) async -> [HKSample] {
        let start = Calendar.current.date(byAdding: .day, value: -14, to: Date())!
        let anchor = Settings.shared.healthAnchor(key).flatMap { try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: $0) }
        return await withCheckedContinuation { cont in
            let q = HKAnchoredObjectQuery(type: type, predicate: HKQuery.predicateForSamples(withStart: start, end: nil), anchor: anchor, limit: HKObjectQueryNoLimit) { _, added, _, newAnchor, _ in
                if let a = newAnchor { Settings.shared.setHealthAnchor(key, try? NSKeyedArchiver.archivedData(withRootObject: a, requiringSecureCoding: true)) }
                cont.resume(returning: added ?? [])
            }
            store.execute(q)
        }
    }

    private func dailySum(_ id: HKQuantityTypeIdentifier, unit: HKUnit, days: Int) async -> [(Date, Double)] {
        let type = HKQuantityType.quantityType(forIdentifier: id)!
        let cal = Calendar.current, today = cal.startOfDay(for: Date()), start = cal.date(byAdding: .day, value: -days, to: today)!
        return await withCheckedContinuation { cont in
            let q = HKStatisticsCollectionQuery(quantityType: type, quantitySamplePredicate: HKQuery.predicateForSamples(withStart: start, end: today), options: .cumulativeSum,
                                                anchorDate: today, intervalComponents: DateComponents(day: 1))
            q.initialResultsHandler = { _, res, _ in
                var out: [(Date, Double)] = []
                res?.enumerateStatistics(from: start, to: today) { st, _ in if let v = st.sumQuantity()?.doubleValue(for: unit) { out.append((st.endDate.addingTimeInterval(-60), v)) } }
                cont.resume(returning: out)
            }
            store.execute(q)
        }
    }

    /// Returns the number of values queued.
    @discardableResult
    func sync() async -> Int {
        guard available, Settings.shared.healthEnabled else { return 0 }
        var out: [Reading] = []
        for (id, param, unit, u) in quantity {
            guard let t = HKObjectType.quantityType(forIdentifier: id) else { continue }
            var samples = await anchored(t, key: id.rawValue).compactMap { $0 as? HKQuantitySample }
            if id == .heartRate {   // last value per 15-minute slot
                samples = Dictionary(grouping: samples) { Int($0.endDate.timeIntervalSince1970 / 900) }.values.compactMap { $0.max { $0.endDate < $1.endDate } }
            }
            for s in samples {
                var v = s.quantity.doubleValue(for: unit)
                if id == .oxygenSaturation { v *= 100 }
                // CGM apps (e.g. Dexcom) write glucose with a device; spot meters are tagged the same way by the app that wrote them
                let isCgm = id == .bloodGlucose && (s.device?.name?.lowercased().contains("dexcom") == true || s.sourceRevision.source.name.lowercased().contains("libre") || s.sourceRevision.source.name.lowercased().contains("dexcom"))
                out.append(Reading(param: param, value: (v * 10).rounded() / 10, unit: u ?? (param == "spo2" ? "%" : param == "hrv" ? "ms" : "/min"), measuredAt: s.endDate,
                                   context: isCgm ? "cgm" : "wearable"))
            }
        }
        for (d, v) in await dailySum(.stepCount, unit: .count(), days: 7) { out.append(Reading(param: "steps", value: v.rounded(), unit: "{steps}", measuredAt: d, context: "wearable")) }
        for (d, v) in await dailySum(.activeEnergyBurned, unit: .kilocalorie(), days: 7) { out.append(Reading(param: "active_energy", value: v.rounded(), unit: "kcal", measuredAt: d, context: "wearable")) }
        if let t = HKObjectType.categoryType(forIdentifier: .sleepAnalysis) {
            let asleep: Set<Int> = [HKCategoryValueSleepAnalysis.asleepCore.rawValue, HKCategoryValueSleepAnalysis.asleepDeep.rawValue, HKCategoryValueSleepAnalysis.asleepREM.rawValue, HKCategoryValueSleepAnalysis.asleepUnspecified.rawValue]
            let nights = Dictionary(grouping: await anchored(t, key: "sleep").compactMap { $0 as? HKCategorySample }.filter { asleep.contains($0.value) }) { Calendar.current.startOfDay(for: $0.endDate) }
            for (_, segs) in nights {
                let hours = segs.reduce(0) { $0 + $1.endDate.timeIntervalSince($1.startDate) } / 3600
                if let end = segs.map(\.endDate).max(), hours > 0.5 { out.append(Reading(param: "sleep_hours", value: (hours * 10).rounded() / 10, unit: "h", measuredAt: end, context: "wearable")) }
            }
        }
        guard !out.isEmpty else { return 0 }
        for chunk in stride(from: 0, to: out.count, by: 400).map({ Array(out[$0..<min($0 + 400, out.count)]) }) {
            await ReadingQueue.shared.add(["device": ["serial": "HK-" + (await deviceName()), "manufacturer": "Apple Health", "model": "HealthKit"], "history": true, "readings": chunk.map { $0.json() }],
                                          summary: "\(chunk.count) values from Apple Health")
        }
        await ReadingQueue.shared.log("Apple Health: \(out.count) values queued")
        return out.count
    }

    @MainActor private func deviceName() -> String { String(UIDevice.current.identifierForVendor?.uuidString.prefix(12) ?? "iphone") }
}

import UIKit
