import Foundation

struct Category: Identifiable, Codable, Hashable, Sendable {
    let id: String
    let name: String

    init(id: String, name: String) {
        self.id = id
        self.name = name
    }

    /// Extracts year from category name (e.g., "2024 Releases" -> 2024)
    var year: Int? {
        let pattern = #"(\d{4})"#
        guard let regex = try? NSRegularExpression(pattern: pattern),
              let match = regex.firstMatch(in: name, range: NSRange(name.startIndex..., in: name)),
              let yearRange = Range(match.range(at: 1), in: name) else {
            return nil
        }
        return Int(name[yearRange])
    }
}

struct Playlist: Codable, Sendable {
    let vodItems: [VODItem]
    let categories: [Category]
    let lastUpdated: Date

    init(vodItems: [VODItem], categories: [Category], lastUpdated: Date = Date()) {
        self.vodItems = vodItems
        self.categories = categories
        self.lastUpdated = lastUpdated
    }

    var categorizedVODItems: [String: [VODItem]] {
        Dictionary(grouping: vodItems) { item in
            item.categoryID ?? "Uncategorized"
        }
    }

    func vodItems(forCategory categoryID: String) -> [VODItem] {
        vodItems.filter { $0.categoryID == categoryID }
    }

    var isEmpty: Bool {
        vodItems.isEmpty
    }

    var count: Int {
        vodItems.count
    }
}
