//
//  AmbientLightService.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/10/25.
//

import Foundation
import UIKit
import Observation
import Bedrock

/// Service for monitoring ambient light and managing brightness
@Observable
class AmbientLightService {
    
    // MARK: - Properties
    private(set) var currentBrightness: Double = 1.0
    private(set) var isMonitoring = false
    
    // Timer for periodic brightness checks
    private var brightnessTimer: Timer?
    
    // Callback for brightness changes
    var onBrightnessChange: (() -> Void)?
    
    // MARK: - Singleton
    static let shared = AmbientLightService()
    
    private init() {
        // Private initializer for singleton
    }
    
    // MARK: - Public Interface
    
    /// Start monitoring ambient light and brightness
    func startMonitoring() {
        guard !isMonitoring else { return }
        
        isMonitoring = true
        updateCurrentBrightness()
        
        // Check brightness every 5 seconds
        brightnessTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
            self?.updateCurrentBrightness()
        }
    }
    
    /// Stop monitoring ambient light and brightness
    func stopMonitoring() {
        guard isMonitoring else { return }
        
        isMonitoring = false
        brightnessTimer?.invalidate()
        brightnessTimer = nil
    }
    
    /// Set screen brightness (0.0 to 1.0)
    func setBrightness(_ brightness: Double) {
        let clampedBrightness = max(0.0, min(1.0, brightness))
        let previousBrightness = UIScreen.main.brightness
        
        Design.debugLog("[ambient] AmbientLightService.setBrightness:")
        Design.debugLog("[ambient]   - Requested brightness: \(String(format: "%.2f", brightness))")
        Design.debugLog("[ambient]   - Clamped brightness: \(String(format: "%.2f", clampedBrightness))")
        Design.debugLog("[ambient]   - Previous screen brightness: \(String(format: "%.2f", previousBrightness))")
        
        UIScreen.main.brightness = clampedBrightness
        currentBrightness = clampedBrightness
        
        Design.debugLog("[ambient]   - New screen brightness: \(String(format: "%.2f", UIScreen.main.brightness))")
        Design.debugLog("[ambient]   - Service currentBrightness: \(String(format: "%.2f", currentBrightness))")
    }
    
    /// Get current screen brightness
    func getCurrentBrightness() -> Double {
        return UIScreen.main.brightness
    }
    
    /// Check if ambient light is below threshold
    func isAmbientLightLow(threshold: Double) -> Bool {
        return currentBrightness < threshold
    }
    
    // MARK: - Private Methods
    
    private func updateCurrentBrightness() {
        let newBrightness = UIScreen.main.brightness
        if abs(newBrightness - currentBrightness) > 0.05 { // Only update if significant change
            let previousBrightness = currentBrightness
            currentBrightness = newBrightness
            
            Design.debugLog("[ambient] AmbientLightService: Brightness changed from \(String(format: "%.2f", previousBrightness)) to \(String(format: "%.2f", newBrightness))")
            
            // Notify that brightness changed
            onBrightnessChange?()
        }
    }
}
