import Foundation

/// Parsers for Bluetooth SIG standard health profiles (GATT Specification Supplement).
/// Same logic and test vectors as the Android app (GattParsers.kt). Pure Swift: no CoreBluetooth import, unit-testable.
enum GattParsers {
    // Services (16-bit)
    static let svcBloodPressure = "1810", svcThermometer = "1809", svcGlucose = "1808", svcPulseOximeter = "1822"
    static let svcWeightScale = "181D", svcBodyComposition = "181B", svcHeartRate = "180D", svcBattery = "180F", svcDeviceInfo = "180A"
    static let healthServices = [svcBloodPressure, svcThermometer, svcGlucose, svcPulseOximeter, svcWeightScale, svcBodyComposition, svcHeartRate]
    // Characteristics
    static let chBP = "2A35", chTemp = "2A1C", chGlucose = "2A18", chGlucoseContext = "2A34", chRACP = "2A52"
    static let chPlxSpot = "2A5E", chPlxContinuous = "2A5F", chWeight = "2A9D", chBodyComposition = "2A9C", chHeartRate = "2A37"
    static let chBattery = "2A19", chSerial = "2A25", chManufacturer = "2A29", chModel = "2A24", chFirmware = "2A26"
    static let measurementChars: Set<String> = [chBP, chTemp, chGlucose, chRACP, chPlxSpot, chPlxContinuous, chWeight, chBodyComposition, chHeartRate, chGlucoseContext]

    /// Accept the device clock only if within 2 days of the phone clock (many devices are never set).
    static let maxSkew: TimeInterval = 2 * 24 * 3600

    // MARK: number formats
    static func u8(_ b: [UInt8], _ o: Int) -> Int { Int(b[o]) }
    static func u16(_ b: [UInt8], _ o: Int) -> Int { Int(b[o]) | (Int(b[o + 1]) << 8) }
    static func s16(_ b: [UInt8], _ o: Int) -> Int { Int(Int16(bitPattern: UInt16(u16(b, o)))) }

    /// IEEE-11073 16-bit SFLOAT. nil for NaN / NRes / ±INF / reserved.
    static func sfloat(_ b: [UInt8], _ o: Int) -> Double? {
        let raw = u16(b, o)
        if [0x07FF, 0x0800, 0x07FE, 0x0802, 0x0801].contains(raw) { return nil }
        var mantissa = raw & 0x0FFF
        var exponent = raw >> 12
        if mantissa >= 0x0800 { mantissa -= 0x1000 }
        if exponent >= 0x0008 { exponent -= 0x0010 }
        return Double(mantissa) * pow(10.0, Double(exponent))
    }

    /// IEEE-11073 32-bit FLOAT.
    static func float32(_ b: [UInt8], _ o: Int) -> Double? {
        let raw = Int(b[o]) | (Int(b[o + 1]) << 8) | (Int(b[o + 2]) << 16)
        if [0x7FFFFF, 0x800000, 0x7FFFFE, 0x800002, 0x800001].contains(raw) { return nil }
        let mantissa = raw >= 0x800000 ? raw - 0x1000000 : raw
        let exponent = Int(Int8(bitPattern: b[o + 3]))
        return Double(mantissa) * pow(10.0, Double(exponent))
    }

    /// 7-byte Date Time in the phone's time zone; nil if unset / invalid.
    static func dateTime(_ b: [UInt8], _ o: Int, tz: TimeZone = .current) -> Date? {
        let year = u16(b, o), month = u8(b, o + 2), day = u8(b, o + 3)
        guard year >= 2000, (1...12).contains(month), (1...31).contains(day) else { return nil }
        var c = DateComponents(); c.year = year; c.month = month; c.day = day; c.hour = u8(b, o + 4); c.minute = u8(b, o + 5); c.second = u8(b, o + 6)
        var cal = Calendar(identifier: .gregorian); cal.timeZone = tz
        return cal.date(from: c)
    }

    static func pickTime(_ device: Date?, _ now: Date, trustDevice: Bool = false) -> Date {
        guard let d = device, (trustDevice || abs(d.timeIntervalSince(now)) < maxSkew), d <= now.addingTimeInterval(300) else { return now }
        return d
    }

    // MARK: Blood Pressure Measurement 0x2A35
    static func bloodPressure(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0), kPa = flags & 0x01 != 0
        var o = 1
        let sys = sfloat(b, o), dia = sfloat(b, o + 2), map = sfloat(b, o + 4); o += 6
        var t: Date? = nil
        if flags & 0x02 != 0 { t = dateTime(b, o); o += 7 }
        var pulse: Double? = nil
        if flags & 0x04 != 0 && b.count >= o + 2 { pulse = sfloat(b, o); o += 2 }
        let ts = pickTime(t, now), unit = kPa ? "kPa" : "mmHg"
        return [sys.map { Reading(param: "bp_sys", value: $0, unit: unit, measuredAt: ts) }, dia.map { Reading(param: "bp_dia", value: $0, unit: unit, measuredAt: ts) },
                map.map { Reading(param: "bp_map", value: $0, unit: unit, measuredAt: ts) }, pulse.map { Reading(param: "pulse", value: $0, unit: "/min", measuredAt: ts) }].compactMap { $0 }
    }

    // MARK: Temperature Measurement 0x2A1C
    static func temperature(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0)
        guard let v = float32(b, 1) else { return [] }
        var t: Date? = nil
        if flags & 0x02 != 0 && b.count >= 12 { t = dateTime(b, 5) }
        return [Reading(param: "temp", value: v, unit: flags & 0x01 != 0 ? "[degF]" : "Cel", measuredAt: pickTime(t, now))]
    }

    // MARK: Glucose Measurement 0x2A18
    static func glucose(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0)
        var o = 1
        let seq = u16(b, o); o += 2
        var base = dateTime(b, o); o += 7
        if flags & 0x01 != 0 { let off = s16(b, o); o += 2; base = base?.addingTimeInterval(Double(off) * 60) }
        guard flags & 0x02 != 0, let conc = sfloat(b, o) else { return [] }
        let mol = flags & 0x04 != 0
        let (value, unit) = mol ? (conc * 1000.0, "mmol/L") : (conc * 100000.0, "mg/dL")
        return [Reading(param: "glucose", value: (value * 10).rounded() / 10, unit: unit, measuredAt: pickTime(base, now, trustDevice: true), sequence: seq)]
    }

    /// Glucose Measurement Context 0x2A34 → (sequence, meal context)
    static func glucoseContext(_ b: [UInt8]) -> (Int, String?)? {
        guard b.count >= 3 else { return nil }
        let flags = u8(b, 0), seq = u16(b, 1)
        var o = 3
        if flags & 0x80 != 0 { o += 1 }
        if flags & 0x01 != 0 { o += 3 }
        if flags & 0x02 != 0 && b.count > o {
            let m: [Int: String] = [1: "pre_meal", 2: "post_meal", 3: "fasting", 4: "random", 5: "bedtime"]
            return (seq, m[u8(b, o)])
        }
        return (seq, nil)
    }

    /// RACP: report all stored records, or those with sequence >= fromSeq.
    static func racpReport(_ fromSeq: Int?) -> [UInt8] {
        guard let s = fromSeq else { return [0x01, 0x01] }
        return [0x01, 0x03, 0x01, UInt8(s & 0xFF), UInt8((s >> 8) & 0xFF)]
    }

    // MARK: PLX 0x2A5E / 0x2A5F
    static func plxSpot(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0), spo2 = sfloat(b, 1), pr = sfloat(b, 3)
        var o = 5
        var t: Date? = nil
        if flags & 0x01 != 0 { if b.count >= o + 7 { t = dateTime(b, o) }; o += 7 }
        if flags & 0x02 != 0 { o += 2 }
        if flags & 0x04 != 0 { o += 3 }
        let pai = (flags & 0x08 != 0 && b.count >= o + 2) ? sfloat(b, o) : nil
        let ts = pickTime(t, now)
        return [spo2.map { Reading(param: "spo2", value: $0, unit: "%", measuredAt: ts) }, pr.map { Reading(param: "pulse", value: $0, unit: "/min", measuredAt: ts) },
                pai.map { Reading(param: "pi", value: $0, unit: "%", measuredAt: ts) }].compactMap { $0 }
    }

    static func plxContinuous(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0), spo2 = sfloat(b, 1), pr = sfloat(b, 3)
        var o = 5
        if flags & 0x01 != 0 { o += 4 }
        if flags & 0x02 != 0 { o += 4 }
        if flags & 0x04 != 0 { o += 2 }
        if flags & 0x08 != 0 { o += 3 }
        let pai = (flags & 0x10 != 0 && b.count >= o + 2) ? sfloat(b, o) : nil
        return [spo2.map { Reading(param: "spo2", value: $0, unit: "%", measuredAt: now) }, pr.map { Reading(param: "pulse", value: $0, unit: "/min", measuredAt: now) },
                pai.map { Reading(param: "pi", value: $0, unit: "%", measuredAt: now) }].compactMap { $0 }
    }

    // MARK: Weight 0x2A9D
    static func weight(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0), imperial = flags & 0x01 != 0, raw = u16(b, 1)
        if raw == 0xFFFF { return [] }
        let w = Double(raw) * (imperial ? 0.01 : 0.005)
        var o = 3
        var t: Date? = nil
        if flags & 0x02 != 0 { t = dateTime(b, o); o += 7 }
        if flags & 0x04 != 0 { o += 1 }
        var bmi: Double? = nil
        if flags & 0x08 != 0 && b.count >= o + 4 { bmi = Double(u16(b, o)) * 0.1 }
        let ts = pickTime(t, now)
        var out = [Reading(param: "weight", value: (w * 100).rounded() / 100, unit: imperial ? "[lb_av]" : "kg", measuredAt: ts)]
        if let m = bmi { out.append(Reading(param: "bmi", value: (m * 10).rounded() / 10, unit: "kg/m2", measuredAt: ts)) }
        return out
    }

    // MARK: Body Composition 0x2A9C
    static func bodyComposition(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u16(b, 0), imperial = flags & 0x0001 != 0, fatRaw = u16(b, 2)
        var o = 4
        var t: Date? = nil
        if flags & 0x0002 != 0 { if b.count >= o + 7 { t = dateTime(b, o) }; o += 7 }
        if flags & 0x0004 != 0 { o += 1 }
        for bit in [0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200] where flags & bit != 0 { o += 2 }
        var w: Double? = nil
        if flags & 0x0400 != 0 && b.count >= o + 2 { w = Double(u16(b, o)) * (imperial ? 0.01 : 0.005) }
        let ts = pickTime(t, now)
        var out: [Reading] = []
        if fatRaw != 0xFFFF { out.append(Reading(param: "body_fat", value: Double(fatRaw) * 0.1, unit: "%", measuredAt: ts)) }
        if let w { out.append(Reading(param: "weight", value: (w * 100).rounded() / 100, unit: imperial ? "[lb_av]" : "kg", measuredAt: ts)) }
        return out
    }

    // MARK: Heart Rate 0x2A37
    static func heartRate(_ b: [UInt8], now: Date = Date()) -> [Reading] {
        let flags = u8(b, 0)
        let hr = flags & 0x01 != 0 ? u16(b, 1) : u8(b, 1)
        return (20...300).contains(hr) ? [Reading(param: "hr", value: Double(hr), unit: "/min", measuredAt: now)] : []
    }

    /// Route a characteristic (16-bit uppercase code) to its parser; malformed packets are ignored.
    static func parse(_ characteristic: String, _ value: [UInt8], now: Date = Date()) -> [Reading] {
        let minLen: [String: Int] = [chBP: 7, chTemp: 5, chGlucose: 10, chPlxSpot: 5, chPlxContinuous: 5, chWeight: 3, chBodyComposition: 4, chHeartRate: 2]
        guard let need = minLen[characteristic], value.count >= need else { return [] }
        switch characteristic {
        case chBP: return value.count >= ((value[0] & 0x02) != 0 ? 14 : 7) ? bloodPressure(value, now: now) : []
        case chTemp: return temperature(value, now: now)
        case chGlucose: return value.count >= ((value[0] & 0x01) != 0 ? 14 : 12) ? glucose(value, now: now) : []
        case chPlxSpot: return plxSpot(value, now: now)
        case chPlxContinuous: return plxContinuous(value, now: now)
        case chWeight: return value.count >= ((value[0] & 0x02) != 0 ? 10 : 3) ? weight(value, now: now) : []
        case chBodyComposition: return bodyComposition(value, now: now)
        case chHeartRate: return value.count >= ((value[0] & 0x01) != 0 ? 3 : 2) ? heartRate(value, now: now) : []
        default: return []
        }
    }
}
