import Foundation

/// OLT resources and device actions.
@MainActor
final class OLTRepository {
    private let client: APIClient
    init(client: APIClient) { self.client = client }

    func configs(query: APIQuery = .empty) async throws -> [OLTConfigDoc] {
        try await client.get(.oltConfigs, query: query, as: [OLTConfigDoc].self)
    }

    func allConfigs() async throws -> [OLTConfigDoc] {
        try await client.getAll(.oltConfigs, idOf: { $0.documentId })
    }

    /// Map of OLT id → operator name (`OLT.Name`), via projection. Skips names
    /// equal to the id, so only real labels come through.
    func nameMap() async throws -> [String: String] {
        var query = APIQuery()
        query.projection = ["OLT.Name": 1]
        let configs: [OLTConfigDoc] = try await client.getAll(.oltConfigs, baseQuery: query, idOf: { $0.documentId })
        return configs.reduce(into: [:]) { map, config in
            if let name = config.name, !name.isEmpty, name != config.id { map[config.id] = name }
        }
    }

    func config(id: String) async throws -> OLTConfigDoc {
        try await client.get(.oltConfig(id: id), as: OLTConfigDoc.self)
    }

    // MARK: OLT-STATE / ONU registration

    func states(query: APIQuery = .empty) async throws -> [OLTStateDoc] {
        try await client.get(.oltStates, query: query, as: [OLTStateDoc].self)
    }

    func allStates() async throws -> [OLTStateDoc] {
        try await client.getAll(.oltStates, idOf: { $0.documentId })
    }

    func state(id: String) async throws -> OLTStateDoc {
        try await client.get(.oltState(id: id), as: OLTStateDoc.self)
    }

    /// Resolve every ONU's registration state by inverting the OLT-STATE
    /// `"ONU States"` buckets (dev guide Procedure 2).
    func registrationMap() async throws -> [String: ONULifecycleState] {
        Self.registrationMap(from: try await allStates())
    }

    /// Pure inversion of OLT-STATE buckets → `onuId: state`. On the rare ONU
    /// that appears twice, prefer the non-`Registered` bucket — that's the
    /// interesting signal (field guide §3.11).
    static func registrationMap(from olts: [OLTStateDoc]) -> [String: ONULifecycleState] {
        var map: [String: ONULifecycleState] = [:]
        for olt in olts {
            for (bucket, ids) in olt.onuStatesByBucket {
                let state = ONULifecycleState(rawValue: bucket) ?? .unknown
                for id in ids {
                    if let existing = map[id] {
                        if existing == .registered && state != .registered { map[id] = state }
                    } else {
                        map[id] = state
                    }
                }
            }
        }
        return map
    }

    func stats(id: String, lastHours: Int = 24) async throws -> [StatSample] {
        try await client.get(.oltStats(id: id),
                             query: .window(lastHours: lastHours),
                             as: [StatSample].self)
    }

    func logs(id: String, lastHours: Int = 24) async throws -> [LogEntry] {
        try await client.get(.oltLogs(id: id),
                             query: .window(lastHours: lastHours),
                             as: [LogEntry].self)
    }

    // MARK: Actions

    /// `PUT /olts/<id>/reset/` — reboots the OLT. Service-affecting.
    func reset(id: String) async throws {
        let _: JSONValue = try await client.action("PUT", .oltReset(id: id), as: JSONValue.self)
    }

    // NOTE: the four methods below (disable-onu / broadcast-enable + their pending
    // reads) are not yet wired to any screen. Their request shapes are documented
    // but UNEXERCISED — verify against a live box before building UI on them.

    /// `PUT /olts/<olt>/disable-onu/<onu>/` with body `{ "disable": Bool }` (unwrapped).
    func setONUDisabled(olt: String, onu: String, disabled: Bool) async throws {
        let _: JSONValue = try await client.send(
            "PUT", .oltDisableONU(olt: olt, onu: onu),
            body: DisableONURequest(disable: disabled),
            wrapInData: false, as: JSONValue.self)
    }

    /// `GET /olts/<olt>/disable-onu/<onu>/` → pending status of the action.
    func disableONUPending(olt: String, onu: String) async throws -> Bool {
        let status: PendingStatus = try await client.get(
            .oltDisableONU(olt: olt, onu: onu), as: PendingStatus.self)
        return status.pending
    }

    /// `PUT /olts/<olt>/broadcast-enable-onus/`
    func broadcastEnableONUs(olt: String) async throws {
        let _: JSONValue = try await client.action(
            "PUT", .oltBroadcastEnableONUs(olt: olt), as: JSONValue.self)
    }

    func broadcastEnablePending(olt: String) async throws -> Bool {
        let status: PendingStatus = try await client.get(
            .oltBroadcastEnableONUs(olt: olt), as: PendingStatus.self)
        return status.pending
    }
}

/// PON Controller resources.
@MainActor
final class ControllerRepository {
    private let client: APIClient
    init(client: APIClient) { self.client = client }

    func configs(query: APIQuery = .empty) async throws -> [ControllerConfigDoc] {
        try await client.get(.controllerConfigs, query: query, as: [ControllerConfigDoc].self)
    }

    func allConfigs() async throws -> [ControllerConfigDoc] {
        try await client.getAll(.controllerConfigs, idOf: { $0.documentId })
    }

    func config(id: String) async throws -> ControllerConfigDoc {
        try await client.get(.controllerConfig(id: id), as: ControllerConfigDoc.self)
    }

    func stats(id: String, lastHours: Int = 24) async throws -> [StatSample] {
        try await client.get(.controllerStats(id: id),
                             query: .window(lastHours: lastHours),
                             as: [StatSample].self)
    }

    func logs(id: String, lastHours: Int = 24) async throws -> [LogEntry] {
        try await client.get(.controllerLogs(id: id),
                             query: .window(lastHours: lastHours),
                             as: [LogEntry].self)
    }
}
