// Benchmarks the shipping speech engines on the documented sample set.
//   sayburst-bench download <modelID>...
//   sayburst-bench run <modelID>... [--out file.json]
// Models install to the same place the app uses, verified with SHA-256.
import AVFoundation
import Foundation
import SayburstKit
import SayburstSpeech

struct CatalogModel: Codable { let id: String; let engine: String; let fluidVersion: String?; let revision: String; let files: [ModelFile]; let name: String }
struct Catalog: Codable { let models: [CatalogModel] }
struct Sample: Codable { let id: String; let set: String; let file: String; let reference: String; let spoken: String? }

let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
let catalog = try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: root.appendingPathComponent("app/Sayburst/Resources/ModelCatalog.json")))
let modelsDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("Sayburst/Models")

func installDir(_ m: CatalogModel) -> URL { modelsDir.appendingPathComponent("\(m.id)@\(m.revision.prefix(10))") }
func model(_ id: String) -> CatalogModel {
    guard let m = catalog.models.first(where: { $0.id == id }) else { fatalError("unknown model \(id)") }
    return m
}

func loadSamples(_ url: URL) throws -> [Float] {
    let file = try AVAudioFile(forReading: url)
    let target = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!
    let converter = AVAudioConverter(from: file.processingFormat, to: target)!
    var out: [Float] = []
    let inBuf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: 32_768)!
    while true {
        let buf = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: 32_768)!
        var err: NSError?
        let status = converter.convert(to: buf, error: &err) { _, st in
            do { try file.read(into: inBuf) } catch { st.pointee = .endOfStream; return nil }
            if inBuf.frameLength == 0 { st.pointee = .endOfStream; return nil }
            st.pointee = .haveData; return inBuf
        }
        if let ch = buf.floatChannelData?[0], buf.frameLength > 0 { out += UnsafeBufferPointer(start: ch, count: Int(buf.frameLength)) }
        if status != .haveData { break }
    }
    return out
}

/// Simple normalizer: lowercase, drop punctuation, collapse spaces. Digits are not
/// spelled out, so number formatting differences count as errors (stated in the report).
func normalize(_ s: String) -> [String] {
    let lowered = s.lowercased().replacingOccurrences(of: "’", with: "'")
    let cleaned = lowered.unicodeScalars.map { CharacterSet.alphanumerics.contains($0) || $0 == "'" || $0 == " " ? Character($0) : " " }
    return String(cleaned).split(separator: " ").map(String.init)
}

func wordErrors(_ ref: [String], _ hyp: [String]) -> Int {
    var d = Array(0...hyp.count)
    for i in 1...max(1, ref.count) where !ref.isEmpty {
        var prev = d[0]; d[0] = i
        for j in 1...max(1, hyp.count) where !hyp.isEmpty {
            let tmp = d[j]
            d[j] = min(d[j] + 1, d[j - 1] + 1, prev + (ref[i - 1] == hyp[j - 1] ? 0 : 1))
            prev = tmp
        }
    }
    return ref.isEmpty ? hyp.count : (hyp.isEmpty ? ref.count : d[hyp.count])
}

func residentMB() -> Double {
    var info = mach_task_basic_info()
    var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
    let kr = withUnsafeMutablePointer(to: &info) { $0.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(MACH_TASK_BASIC_INFO), $0, &count) } }
    return kr == KERN_SUCCESS ? Double(info.resident_size) / 1_048_576 : -1
}

let args = Array(CommandLine.arguments.dropFirst())
guard let command = args.first else { print("usage: sayburst-bench download|run <modelID>..."); exit(1) }
let ids = args.dropFirst().prefix { !$0.hasPrefix("--") }

switch command {
case "download":
    for id in ids {
        let m = model(id)
        let d = ModelDownloader(resumeDirectory: modelsDir.appendingPathComponent("../Downloads"))
        let start = Date()
        var last = -1
        try await d.install(files: m.files, into: installDir(m)) { p in
            let pct = Int(p.fraction * 100)
            if pct / 10 != last / 10 { last = pct; print("\(id): \(pct)%") }
        }
        print("\(id): installed and verified in \(String(format: "%.0f", Date().timeIntervalSince(start)))s")
    }

case "run":
    let manifest = try JSONDecoder().decode([Sample].self, from: Data(contentsOf: root.appendingPathComponent("bench/samples/manifest.json")))
    var report: [[String: Any]] = []
    for id in ids {
        let m = model(id)
        let baseRSS = residentMB()
        let t0 = Date()
        let engine: SpeechEngine = m.engine == "parakeet"
            ? try await ParakeetEngine(modelID: m.id, directory: installDir(m), fluidVersion: m.fluidVersion ?? "v3")
            : try WhisperEngine(modelID: m.id, fileURL: installDir(m).appendingPathComponent(m.files[0].relativePath))
        let loadSec = Date().timeIntervalSince(t0)
        // Warm-up (first inference compiles kernels); not timed.
        _ = try await engine.transcribe(samples: try loadSamples(root.appendingPathComponent("bench/" + manifest[0].file)), language: "en", vocabulary: [])
        var refWords = 0, errors = 0, audioSec = 0.0, procSec = 0.0
        var dictationLatencies: [Double] = []
        var rows: [[String: Any]] = []
        for s in manifest {
            let samples = try loadSamples(root.appendingPathComponent("bench/" + s.file))
            let dur = Double(samples.count) / 16_000
            let start = Date()
            let r = try await engine.transcribe(samples: samples, language: "en", vocabulary: s.id == "say-vocab" ? ["GitHub", "Sayburst"] : [])
            let elapsed = Date().timeIntervalSince(start)
            let ref = normalize(s.reference), hyp = normalize(r.text)
            let e = wordErrors(ref, hyp)
            if s.set.hasPrefix("librispeech") { refWords += ref.count; errors += e; audioSec += dur; procSec += elapsed }
            else { dictationLatencies.append(elapsed) }
            let cleaned = TextPipeline(vocabulary: s.id == "say-vocab" ? ["GitHub", "Sayburst"] : []).process(r.text)
            rows.append(["id": s.id, "set": s.set, "audioSec": dur, "elapsedMs": Int(elapsed * 1000), "wordErrors": e, "refWords": ref.count, "raw": r.text, "cleaned": cleaned])
        }
        dictationLatencies.sort()
        let peak = residentMB()
        let summary: [String: Any] = [
            "model": id, "loadSeconds": loadSec,
            "librispeechWER": Double(errors) / Double(max(1, refWords)), "librispeechWords": refWords,
            "realtimeFactor": audioSec / max(procSec, 0.0001),
            "dictationMedianMs": Int(dictationLatencies[dictationLatencies.count / 2] * 1000),
            "dictationMaxMs": Int((dictationLatencies.last ?? 0) * 1000),
            "rssDeltaMB": peak - baseRSS, "samples": rows,
        ]
        print(String(format: "%@  WER %.2f%% (%d words)  speed %.0fx realtime  dictation median %d ms  load %.1fs  +%.0f MB",
                     id, (summary["librispeechWER"] as! Double) * 100, refWords, summary["realtimeFactor"] as! Double,
                     summary["dictationMedianMs"] as! Int, loadSec, peak - baseRSS))
        report.append(summary)
    }
    if let i = args.firstIndex(of: "--out"), i + 1 < args.count {
        var host = utsname(); uname(&host)
        let meta: [String: Any] = [
            "date": ISO8601DateFormatter().string(from: Date()),
            "os": ProcessInfo.processInfo.operatingSystemVersionString,
            "machine": withUnsafePointer(to: &host.machine) { $0.withMemoryRebound(to: CChar.self, capacity: 256) { String(cString: $0) } },
            "memoryGB": ProcessInfo.processInfo.physicalMemory / 1_073_741_824,
            "results": report,
        ]
        try JSONSerialization.data(withJSONObject: meta, options: [.prettyPrinted, .sortedKeys]).write(to: URL(fileURLWithPath: args[i + 1]))
    }
default:
    print("unknown command")
}
