//
//  WakeLockService.swift
//  AudioPlaybackKit
//
//  Created by Matt Bruce on 9/8/25.
//

#if canImport(UIKit)
import UIKit
#endif
import Observation

/// Service to manage screen wake lock and prevent device from sleeping
@available(iOS 17.0, tvOS 17.0, *)
@Observable
public class WakeLockService {
    
    // MARK: - Singleton
    public static let shared = WakeLockService()
    
    // MARK: - Properties
    public private(set) var isWakeLockActive = false
    private var wakeLockTimer: Timer?
    
    // MARK: - Initialization
    private init() {}
    
    deinit {
        disableWakeLock()
    }
    
    // MARK: - Public Interface
    
    /// Enable wake lock to prevent device from sleeping
    public func enableWakeLock() {
        guard !isWakeLockActive else { return }
        
        #if canImport(UIKit)
        // Prevent device from sleeping
        UIApplication.shared.isIdleTimerDisabled = true
        
        // Set up periodic timer to maintain wake lock
        wakeLockTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true) { _ in
            // Keep the app active by briefly enabling/disabling idle timer
            UIApplication.shared.isIdleTimerDisabled = false
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                UIApplication.shared.isIdleTimerDisabled = true
            }
        }
        #endif
        
        isWakeLockActive = true
        print("🔒 Wake lock enabled - device will not sleep")
    }
    
    /// Disable wake lock and allow device to sleep normally
    public func disableWakeLock() {
        guard isWakeLockActive else { return }
        
        #if canImport(UIKit)
        // Allow device to sleep normally
        UIApplication.shared.isIdleTimerDisabled = false
        #endif
        
        // Stop the maintenance timer
        wakeLockTimer?.invalidate()
        wakeLockTimer = nil
        
        isWakeLockActive = false
        print("🔓 Wake lock disabled - device can sleep normally")
    }
    
    /// Toggle wake lock state
    public func toggleWakeLock() {
        if isWakeLockActive {
            disableWakeLock()
        } else {
            enableWakeLock()
        }
    }
    
    /// Check if wake lock is currently active
    public var isActive: Bool {
        return isWakeLockActive
    }
}
