import AppIntents
import Foundation

/// Toggles the climbing session state: starts a session if none is active, or ends the current one.
struct ToggleSessionIntent: AppIntent {

    static var title: LocalizedStringResource {
        "Toggle Climbing Session"
    }

    static var description: IntentDescription {
        IntentDescription(
            "Starts a new session at your last gym if you're not climbing, or ends your current session if you are."
        )
    }

    static var openAppWhenRun: Bool {
        false
    }

    func perform() async throws -> some IntentResult & ProvidesDialog {
        // Wait for app initialization
        try? await Task.sleep(nanoseconds: 1_000_000_000)

        let controller = await SessionIntentController()
        let (summary, wasStarted) = try await controller.toggleSession()

        if wasStarted {
            // Wait for Live Activity
            try? await Task.sleep(nanoseconds: 500_000_000)
            return .result(dialog: IntentDialog("Session started at \(summary.gymName). Have an awesome climb!"))
        } else {
            return .result(dialog: IntentDialog("Session at \(summary.gymName) ended. Nice work!"))
        }
    }

    static var parameterSummary: some ParameterSummary {
        Summary("Toggle my climbing session")
    }
}
