import UIKit
import ComposeApp

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)

        // Parse unattended experiment-mode launch args.
        // Accepts single-dash `-key value` pairs after a `--` separator (matches
        // `xcrun devicectl device process launch ... -- -key value` convention).
        let args = CommandLine.arguments
        var modelName: String? = nil
        var durationMs: Int64 = 0
        var startAtWallMs: Int64 = 0
        var finishOnStop: Bool = true
        var i = 0
        while i < args.count - 1 {
            let k = args[i]
            let v = args[i + 1]
            switch k {
            case "-test_model":
                modelName = v
            case "-test_duration_sec":
                if let secs = Int64(v) { durationMs = secs * 1000 }
            case "-test_duration_ms":
                durationMs = Int64(v) ?? 0
            case "-start_at_wall_ms":
                startAtWallMs = Int64(v) ?? 0
            case "-finish_on_stop":
                finishOnStop = (v == "1" || v.lowercased() == "true")
            default: break
            }
            i += 1
        }

        let rootVc: UIViewController
        if let name = modelName, durationMs > 0 {
            NSLog("[ExperimentAuto] launching with modelName=\(name) durationMs=\(durationMs) startAtWallMs=\(startAtWallMs)")
            rootVc = MainKt.MainViewControllerWithAutoSpec(
                modelName: name,
                startAtWallMs: startAtWallMs,
                durationMs: durationMs,
                finishOnStop: finishOnStop
            )
        } else {
            rootVc = MainKt.MainViewController()
        }

        if let window = window {
            window.rootViewController = rootVc
            window.makeKeyAndVisible()
        }
        return true
    }
}
