//
//  LiveActivityManager.swift
//  EzTimer
//
//  Created by Jared Evans on 12/17/25.
//

import Foundation
import ActivityKit

class LiveActivityManager {
    static let shared = LiveActivityManager()
    
    private var activity: Activity<TimerAttributes>?
    
    func start(endTime: Date, duration: TimeInterval, message: String) {
        // Ensure Live Activities are supported and enabled
        guard ActivityAuthorizationInfo().areActivitiesEnabled else {
            print("Live Activities are not enabled")
            return
        }
        
        let attributes = TimerAttributes(timerName: "VizTimer")
        let contentState = TimerAttributes.ContentState(endTime: endTime, duration: duration, message: message, isFinished: false)
        
        do {
            // Note: staleDate is nil, meaning the activity content doesn't become stale at a specific time
            // relevanceScore is standard default
            let content = ActivityContent(state: contentState, staleDate: nil)
            
            activity = try Activity.request(attributes: attributes, content: content)
            print("Live Activity started with ID: \(activity?.id ?? "unknown")")
        } catch {
            print("Error starting Live Activity: \(error.localizedDescription)")
        }
    }
    
    func update(endTime: Date, duration: TimeInterval, message: String) {
        guard let activity = activity else { return }
        
        let contentState = TimerAttributes.ContentState(endTime: endTime, duration: duration, message: message, isFinished: false)
        let content = ActivityContent(state: contentState, staleDate: nil)
        
        Task {
            await activity.update(content)
        }
    }
    
    func finish(message: String) {
        guard let activity = activity else { return }
        
        let contentState = TimerAttributes.ContentState(endTime: Date(), duration: 0, message: message, isFinished: true)
        let content = ActivityContent(state: contentState, staleDate: nil)
        
        Task {
            // End with content, but dismissal policy default (keeps it on lock screen)
            await activity.end(content, dismissalPolicy: .default)
            self.activity = nil
        }
    }
    
    func end() {
        guard let activity = activity else { return }
        
        Task {
            // End immediately
            await activity.end(nil, dismissalPolicy: .immediate)
            self.activity = nil
        }
    }
}
