//
//  ChessPrismApp.swift
//  ChessPrism
//
//  Created by Chris Haulmark on 1/6/25.
//

import SwiftUI
import ScreenCaptureKit

@main
struct ChessPrismApp: App {
    @StateObject private var permissionManager = PermissionManager()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(permissionManager)
                .onAppear {
                    permissionManager.requestPermissions()
                }
                .alert(isPresented: $permissionManager.showPermissionAlert) {
                    Alert(
                        title: Text("Permissions Required"),
                        message: Text(permissionManager.permissionAlertMessage),
                        primaryButton: .default(Text("Open Settings")) {
                            NSWorkspace.shared.open(URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy")!)
                        },
                        secondaryButton: .cancel()
                    )
                }
        }
    }
}

class PermissionManager: ObservableObject {
    @Published var showPermissionAlert = false
    @Published var permissionAlertMessage = ""
    
    func requestPermissions() {
        requestScreenRecordingPermission()
        requestAccessibilityPermission()
    }
    
    private func requestScreenRecordingPermission() {
        let status = CGPreflightScreenCaptureAccess()
        if !status {
            permissionAlertMessage += "Screen recording permission is required to analyze chess positions.\n"
            showPermissionAlert = true
        }
    }
    
    private func requestAccessibilityPermission() {
        let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
        if !AXIsProcessTrustedWithOptions(options) {
            permissionAlertMessage += "Accessibility permission is required to interact with other applications.\n"
            showPermissionAlert = true
        }
    }
}
