import Foundation
import AVKit
import SwiftUI
import Combine

@MainActor
class VideoPlayerViewModel: ObservableObject {
    @Published var player: AVPlayer?
    @Published var isPlaying: Bool = false
    @Published var error: Error?

    private var statusObserver: NSKeyValueObservation?

    func setupPlayer(url: URL) {
        print("🎬 Setting up player with URL: \(url)")
        print("🎬 URL scheme: \(url.scheme ?? "none"), host: \(url.host ?? "none")")

        let playerItem = AVPlayerItem(url: url)
        player = AVPlayer(playerItem: playerItem)

        // Observe player item status for loading errors
        statusObserver = playerItem.observe(\.status, options: [.new]) { [weak self] item, _ in
            Task { @MainActor in
                switch item.status {
                case .failed:
                    let error = item.error ?? NSError(
                        domain: "VideoPlayer",
                        code: -1,
                        userInfo: [NSLocalizedDescriptionKey: "Failed to load video"]
                    )
                    print("❌ Player item failed with error: \(error)")
                    print("❌ Error localized description: \(error.localizedDescription)")
                    if let nsError = error as NSError? {
                        print("❌ Error domain: \(nsError.domain), code: \(nsError.code)")
                        print("❌ Error userInfo: \(nsError.userInfo)")
                    }
                    self?.error = error
                case .readyToPlay:
                    print("✅ Video ready to play: \(url)")
                case .unknown:
                    print("⚠️ Video status unknown")
                @unknown default:
                    break
                }
            }
        }

        // Observe playback failures
        NotificationCenter.default.addObserver(
            forName: .AVPlayerItemFailedToPlayToEndTime,
            object: playerItem,
            queue: .main
        ) { [weak self] notification in
            if let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error {
                Task { @MainActor in
                    self?.error = error
                }
            }
        }

        // Observe playback stalls
        NotificationCenter.default.addObserver(
            forName: .AVPlayerItemPlaybackStalled,
            object: playerItem,
            queue: .main
        ) { [weak self] _ in
            Task { @MainActor in
                print("Playback stalled")
            }
        }
    }

    func play() {
        player?.play()
        isPlaying = true
    }

    func pause() {
        player?.pause()
        isPlaying = false
    }

    func cleanup() {
        player?.pause()
        player = nil
        isPlaying = false
        statusObserver?.invalidate()
        statusObserver = nil
        NotificationCenter.default.removeObserver(self)
    }

    deinit {
        statusObserver?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
}
