//
// OpenRocky — Voice-first AI Agent
// https://github.com/openrocky
//
// Developed by everettjf with the assistance of Claude Code and Codex.
// Copyright (c) 2026 everettjf. All rights reserved.
//

import AVFoundation
import UIKit

/// Centralized permission status + request + deep-link helper.
///
/// For voice-first UX the mic state matters most:
///   `.undetermined` — show priming screen, then request
///   `.denied`       — show denied screen with deep-link to Settings
///   `.granted`      — proceed
@MainActor
enum OpenRockyPermissionCenter {
    enum MicrophoneStatus {
        case undetermined
        case denied
        case granted
    }

    static var microphoneStatus: MicrophoneStatus {
        switch AVAudioApplication.shared.recordPermission {
        case .undetermined: .undetermined
        case .denied: .denied
        case .granted: .granted
        @unknown default: .undetermined
        }
    }

    /// Request mic permission. Returns true if granted (either newly or already).
    static func requestMicrophone() async -> Bool {
        if microphoneStatus == .granted { return true }
        return await withCheckedContinuation { continuation in
            AVAudioApplication.requestRecordPermission { granted in
                continuation.resume(returning: granted)
            }
        }
    }

    static func openSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(url)
        }
    }
}
