import Foundation

// MARK: - Cached Regexes for VODItem
/// Pre-compiled regex patterns to avoid repeated compilation
private enum VODItemRegex {
    static let dashYearPattern: NSRegularExpression? = try? NSRegularExpression(pattern: #"- (\d{4})$"#)
    static let parenYearPattern: NSRegularExpression? = try? NSRegularExpression(pattern: #"\((\d{4})\)"#)
}

struct VODItem: Identifiable, Codable, Hashable, Sendable {
    let id: String
    let name: String
    let streamURL: String
    let iconURL: String?
    let categoryID: String?
    let description: String?
    let duration: String?
    let rating: String?
    let added: String?

    init(id: String,
         name: String,
         streamURL: String,
         iconURL: String? = nil,
         categoryID: String? = nil,
         description: String? = nil,
         duration: String? = nil,
         rating: String? = nil,
         added: String? = nil) {
        self.id = id
        self.name = name
        self.streamURL = streamURL
        self.iconURL = iconURL
        self.categoryID = categoryID
        self.description = description
        self.duration = duration
        self.rating = rating
        self.added = added
    }

    var streamURLObject: URL? {
        URL(string: streamURL)
    }

    var iconURLObject: URL? {
        guard let iconURL = iconURL else { return nil }
        return URL(string: iconURL)
    }

    var isMovie: Bool {
        streamURL.contains("/movie/")
    }

    var isTVShow: Bool {
        streamURL.contains("/series/")
    }

    /// Extracts release year from the item name (e.g., "Movie Title - 2025" -> 2025)
    var releaseYear: Int? {
        let nameRange = NSRange(name.startIndex..., in: name)

        // Pattern matches "- YYYY" at the end of the name (common format)
        if let regex = VODItemRegex.dashYearPattern,
           let match = regex.firstMatch(in: name, range: nameRange),
           let yearRange = Range(match.range(at: 1), in: name) {
            return Int(name[yearRange])
        }

        // Fallback: match year in parentheses (2024)
        if let regex = VODItemRegex.parenYearPattern,
           let match = regex.firstMatch(in: name, range: nameRange),
           let yearRange = Range(match.range(at: 1), in: name) {
            return Int(name[yearRange])
        }

        return nil
    }

    /// Sorts VOD items by release date (newest first), using TMDB dates when available
    /// - Parameters:
    ///   - items: The VOD items to sort
    ///   - tmdbDates: Optional dictionary mapping VODItem.id to "YYYY-MM-DD" release dates
    /// - Returns: Sorted array with newest releases first
    static func sortedByReleaseDate(_ items: [VODItem], using tmdbDates: [String: String]? = nil) -> [VODItem] {
        items.sorted { item1, item2 in
            // Try TMDB dates first (format: "YYYY-MM-DD" - sorts correctly as string)
            if let dates = tmdbDates {
                let date1 = dates[item1.id]
                let date2 = dates[item2.id]

                // Both have TMDB dates - compare directly
                if let d1 = date1, let d2 = date2 {
                    if d1 != d2 {
                        return d1 > d2  // Newest first (larger date string = more recent)
                    }
                    return item1.name < item2.name  // Same date, alphabetical
                }

                // Only one has TMDB date - it wins
                if date1 != nil { return true }
                if date2 != nil { return false }
            }

            // Fall back to year extraction from name
            let year1 = item1.releaseYear ?? 0
            let year2 = item2.releaseYear ?? 0
            if year1 != year2 {
                return year1 > year2  // Newest first
            }
            return item1.name < item2.name  // Alphabetical as tiebreaker
        }
    }
}
