import CoreBluetooth
import Foundation

/// Scans for standard Bluetooth health devices (BP, thermometer, glucometer, oximeter, scales, HR straps), subscribes to their
/// measurement characteristics, syncs glucometer memory (RACP) and queues readings with the device identity.
/// iOS does not expose the Bluetooth MAC address, so devices are identified by serial number (0x2A25) or the peripheral UUID.
final class BleCollector: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeripheralDelegate {
    @Published var status = "Ready"
    @Published var last: [Reading] = []
    private var central: CBCentralManager!
    private var peripherals: [UUID: CBPeripheral] = [:]
    private var info: [UUID: [String: String]] = [:]
    private var glucoseContext: [UUID: [Int: String]] = [:]
    private var pending: [UUID: [Reading]] = [:]
    private var flushTimers: [UUID: Timer] = [:]
    private let services = GattParsers.healthServices.map { CBUUID(string: $0) }

    override init() {
        super.init()
        central = CBCentralManager(delegate: self, queue: .main, options: [CBCentralManagerOptionRestoreIdentifierKey: "carepulse-central"])
    }

    func start() {
        guard central.state == .poweredOn else { status = central.state == .poweredOff ? "Turn on Bluetooth" : "Waiting for Bluetooth…"; return }
        status = "Take the reading now – listening…"
        central.scanForPeripherals(withServices: services, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
    }
    func stop() { central.stopScan(); status = "Stopped" }

    // MARK: central
    func centralManagerDidUpdateState(_ c: CBCentralManager) { if c.state == .poweredOn && Settings.shared.autoListen { start() } }
    func centralManager(_ c: CBCentralManager, willRestoreState dict: [String: Any]) {
        for p in (dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral]) ?? [] { peripherals[p.identifier] = p; p.delegate = self }
    }
    func centralManager(_ c: CBCentralManager, didDiscover p: CBPeripheral, advertisementData: [String: Any], rssi: NSNumber) {
        guard peripherals[p.identifier] == nil else { return }
        peripherals[p.identifier] = p; p.delegate = self
        status = "Found \(p.name ?? "device") – connecting…"
        c.connect(p)
    }
    func centralManager(_ c: CBCentralManager, didConnect p: CBPeripheral) { p.discoverServices(services + [CBUUID(string: GattParsers.svcBattery), CBUUID(string: GattParsers.svcDeviceInfo)]) }
    func centralManager(_ c: CBCentralManager, didFailToConnect p: CBPeripheral, error: Error?) { peripherals[p.identifier] = nil }
    func centralManager(_ c: CBCentralManager, didDisconnectPeripheral p: CBPeripheral, error: Error?) {
        flush(p.identifier); peripherals[p.identifier] = nil
        if Settings.shared.autoListen { start() }
    }

    // MARK: peripheral
    func peripheral(_ p: CBPeripheral, didDiscoverServices error: Error?) {
        for s in p.services ?? [] { p.discoverCharacteristics(nil, for: s) }
    }
    func peripheral(_ p: CBPeripheral, didDiscoverCharacteristicsFor s: CBService, error: Error?) {
        for ch in s.characteristics ?? [] {
            let code = ch.uuid.uuidString.uppercased()
            if [GattParsers.chSerial, GattParsers.chManufacturer, GattParsers.chModel, GattParsers.chFirmware, GattParsers.chBattery].contains(code) { p.readValue(for: ch) }
            if GattParsers.measurementChars.contains(code) { p.setNotifyValue(true, for: ch) }
        }
    }
    func peripheral(_ p: CBPeripheral, didUpdateNotificationStateFor ch: CBCharacteristic, error: Error?) {
        // Glucometer: once RACP indications are on, ask for stored records newer than the last one we have
        guard error == nil, ch.uuid.uuidString.uppercased() == GattParsers.chRACP else { return }
        let from = Settings.shared.glucoseSeq(deviceKey(p)).map { $0 + 1 }
        p.writeValue(Data(GattParsers.racpReport(from)), for: ch, type: .withResponse)
    }
    func peripheral(_ p: CBPeripheral, didUpdateValueFor ch: CBCharacteristic, error: Error?) {
        guard let v = ch.value else { return }
        let bytes = [UInt8](v), code = ch.uuid.uuidString.uppercased(), id = p.identifier
        switch code {
        case GattParsers.chSerial: info[id, default: [:]]["serial"] = String(decoding: v, as: UTF8.self).trimmingCharacters(in: .controlCharacters)
        case GattParsers.chManufacturer: info[id, default: [:]]["manufacturer"] = String(decoding: v, as: UTF8.self)
        case GattParsers.chModel: info[id, default: [:]]["model"] = String(decoding: v, as: UTF8.self)
        case GattParsers.chFirmware: info[id, default: [:]]["firmware"] = String(decoding: v, as: UTF8.self)
        case GattParsers.chBattery: if let b = bytes.first { info[id, default: [:]]["battery"] = String(b) }
        case GattParsers.chGlucoseContext: if let (seq, ctx) = GattParsers.glucoseContext(bytes), let ctx { glucoseContext[id, default: [:]][seq] = ctx }
        case GattParsers.chRACP: flush(id)   // record transfer finished
        default:
            let rs = GattParsers.parse(code, bytes)
            guard !rs.isEmpty else { return }
            pending[id, default: []] += rs
            // Devices send several packets (BP + pulse, glucose memory): collect for 1.5 s then queue one batch
            flushTimers[id]?.invalidate()
            flushTimers[id] = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false) { [weak self] _ in self?.flush(id) }
        }
    }

    private func deviceKey(_ p: CBPeripheral) -> String { info[p.identifier]?["serial"] ?? p.identifier.uuidString }

    private func flush(_ id: UUID) {
        guard var rs = pending[id], !rs.isEmpty, let p = peripherals[id] else { return }
        pending[id] = nil
        for i in rs.indices where rs[i].param == "glucose" { if let s = rs[i].sequence, let c = glucoseContext[id]?[s] { rs[i].context = c } }
        if let maxSeq = rs.compactMap({ $0.sequence }).max() { Settings.shared.setGlucoseSeq(deviceKey(p), maxSeq) }
        let i = info[id] ?? [:]
        var device: [String: Any] = ["serial": i["serial"] ?? "ios-" + id.uuidString.prefix(12).lowercased(), "name": p.name ?? "BLE device"]
        if let m = i["manufacturer"] { device["manufacturer"] = m }
        if let m = i["model"] { device["model"] = m }
        if let f = i["firmware"] { device["firmware"] = f }
        if let b = i["battery"], let n = Int(b) { device["battery"] = n }
        if let svc = p.services?.first(where: { GattParsers.healthServices.contains($0.uuid.uuidString.uppercased()) }) { device["ble_service"] = svc.uuid.uuidString.uppercased() }
        var batch: [String: Any] = ["batch_id": "ios-\(Int(Date().timeIntervalSince1970))-\(id.uuidString.prefix(6))", "device": device, "readings": rs.map { $0.json() }]
        let ward = Settings.shared.wardUHID.trimmingCharacters(in: .whitespaces)
        if Settings.shared.config?["patient"] is NSNull || Settings.shared.config?["patient"] == nil, !ward.isEmpty { batch["patient"] = ["uhid": ward] }
        let summary = rs.map { "\($0.param) \($0.value)" }.joined(separator: ", ")
        last = rs; status = "Got it: \(summary)"
        Task { await ReadingQueue.shared.add(batch, summary: summary); await ReadingQueue.shared.log("Reading: \(summary)"); await Uploader.run() }
    }
}
