//
//  RouteFilters.swift
//  SportsTime
//
//  Filters itinerary results based on user preferences.
//  Applied in TripPlanningEngine AFTER scenario planners return.
//

import Foundation
import CoreLocation

enum RouteFilters {

    // MARK: - Repeat Cities Filter

    /// Filter itinerary options that violate repeat city rules.
    /// When allowRepeatCities=false, each city must be visited on exactly ONE day.
    static func filterRepeatCities(
        _ options: [ItineraryOption],
        allow: Bool
    ) -> [ItineraryOption] {
        guard !allow else { return options }
        return options.filter { !hasRepeatCityViolation($0) }
    }

    /// Check if an itinerary visits any city on multiple days.
    static func hasRepeatCityViolation(_ option: ItineraryOption) -> Bool {
        let calendar = Calendar.current
        var cityDays: [String: Set<Date>] = [:]

        for stop in option.stops {
            let city = stop.city
            let day = calendar.startOfDay(for: stop.arrivalDate)
            cityDays[city, default: []].insert(day)
        }

        // Violation if any city has more than 1 day
        return cityDays.values.contains(where: { $0.count > 1 })
    }

    /// Get cities that are visited on multiple days (for error reporting).
    static func findRepeatCities(in options: [ItineraryOption]) -> [String] {
        var violatingCities = Set<String>()
        let calendar = Calendar.current

        for option in options {
            var cityDays: [String: Set<Date>] = [:]
            for stop in option.stops {
                let day = calendar.startOfDay(for: stop.arrivalDate)
                cityDays[stop.city, default: []].insert(day)
            }
            for (city, days) in cityDays where days.count > 1 {
                violatingCities.insert(city)
            }
        }

        return Array(violatingCities).sorted()
    }

}
