import Foundation

/// Historical on-time-performance stats for a given flight key.
///
/// All numbers come straight from the bundled BTS Reporting Carrier
/// On-Time Performance dataset (see ``BTSDataStore`` + the companion
/// ``bts_bundle_meta.json`` citation file). The actor is a thin
/// projection over ``BTSDataStore`` so callers don't have to know the
/// key format.
actor OnTimePerformanceService {

    // MARK: Singleton

    static let shared = OnTimePerformanceService()

    // MARK: Dependencies

    private let store: BTSDataStore

    init(store: BTSDataStore = .shared) {
        self.store = store
    }

    // MARK: Public API

    /// Headline on-time-performance stats for the flight. Returns nil when
    /// the BTS bundle has no record.
    func stat(
        carrier: String,
        flightNumber: Int,
        origin: String,
        dest: String
    ) async -> OnTimeStat? {
        guard let rec = await store.record(
            carrier: carrier,
            flightNumber: flightNumber,
            origin: origin,
            dest: dest
        ) else {
            print("[OnTime] no BTS record for \(carrier)\(flightNumber) \(origin)->\(dest)")
            return nil
        }
        return OnTimeStat(
            onTimePct: rec.onTimePct,
            avgDelayMin: rec.avgDelayMin,
            cancelledPct: rec.cancelledPct,
            samplePeriod: rec.samplePeriod,
            n: rec.totalFlights
        )
    }
}

// MARK: - Stat type

/// Headline on-time stats for a single flight key. ``n`` is the BTS
/// sample size — the UI can use it to render a "based on N flights"
/// caption alongside the percentages.
struct OnTimeStat: Sendable {
    let onTimePct: Double
    let avgDelayMin: Double
    let cancelledPct: Double
    let samplePeriod: String
    let n: Int
}
