import Dispatch
import Foundation

private final class TraceRecorder: @unchecked Sendable {
    private let lock = NSLock()
    private var lines: [String] = []

    func append(_ line: String) {
        lock.lock()
        lines.append(line)
        lock.unlock()
    }

    func snapshot() -> [String] {
        lock.lock()
        defer { lock.unlock() }
        return lines
    }
}

func runSchedulingLab() {
    labHeader(
        "SCHEDULING · QoS expresses intent, not a deterministic order",
        mechanism: "Dispatch communicates urgency to the scheduler; available cores and system load still matter."
    )

    let start = ContinuousClock.now
    let group = DispatchGroup()
    let trace = TraceRecorder()
    let jobs: [(String, DispatchQoS.QoSClass)] = [
        ("background-index", .background),
        ("user-visible-refresh", .userInitiated),
        ("utility-export", .utility),
    ]

    for (name, qos) in jobs {
        group.enter()
        DispatchQueue.global(qos: qos).async {
            trace.append("START \(name) @ \(formatMilliseconds(millisecondsSince(start)))")
            usleep(120_000)
            trace.append("END   \(name) @ \(formatMilliseconds(millisecondsSince(start)))")
            group.leave()
        }
    }

    group.wait()
    trace.snapshot().forEach { print($0) }
    print("Observation: each job did equal simulated work, yet start and finish ordering may vary across runs.")
    print("Interview link: QoS is policy input, not a promise of sequence, timing, or thread identity.")
}
