import Foundation

/// Curated YouTube-video lookup for guide + grammar items (Issue #21).
/// Loads the bundled `youtube_videos.json` at init, serves tense-guide and
/// grammar-note videos by id. The data is static after load; `static let shared`
/// lets services access it without environment injection.
@MainActor
@Observable
final class YouTubeVideoStore {

    struct VideoEntry: Codable, Hashable, Sendable, Identifiable {
        let videoId: String
        let title: String
        var id: String { videoId }
    }

    static let shared = YouTubeVideoStore()

    private(set) var tenseVideos: [String: VideoEntry] = [:]
    private(set) var grammarVideos: [String: VideoEntry] = [:]

    init(bundle: Bundle = .main) {
        load(from: bundle)
    }

    /// Returns the curated video for a tense guide, or nil if unmapped.
    func video(forTenseId id: String) -> VideoEntry? {
        tenseVideos[id]
    }

    /// Returns the curated video for a grammar note, or nil if unmapped.
    func video(forGrammarNoteId id: String) -> VideoEntry? {
        grammarVideos[id]
    }

    /// All distinct videoIds present in the store. Useful for bulk operations
    /// like "download all" or cache cleanup.
    var allVideoIds: Set<String> {
        Set(tenseVideos.values.map(\.videoId)).union(grammarVideos.values.map(\.videoId))
    }

    private func load(from bundle: Bundle) {
        guard let url = bundle.url(forResource: "youtube_videos", withExtension: "json"),
              let data = try? Data(contentsOf: url) else {
            print("[YouTubeVideoStore] bundled youtube_videos.json not found")
            return
        }
        struct Root: Decodable {
            let tenseGuides: [String: VideoEntry]
            let grammarNotes: [String: VideoEntry]
        }
        do {
            let root = try JSONDecoder().decode(Root.self, from: data)
            tenseVideos = root.tenseGuides
            grammarVideos = root.grammarNotes
            print("[YouTubeVideoStore] loaded \(tenseVideos.count) tense + \(grammarVideos.count) grammar entries")
        } catch {
            print("[YouTubeVideoStore] decode failed: \(error)")
        }
    }
}
