import Foundation

/// CEFR-style level for a `Lexeme`, derived from its `frequencyRank`. Lets
/// users gate noun/adjective flashcard sessions by level via a Settings
/// toggle. Cutoffs follow the standard Spanish-frequency-dictionary
/// convention (Davies; RAE CEFR-aligned lists).
///
/// Note: SRS is *not* level-gated. Disabling a level only stops *new*
/// cards from that band entering the session pool — already-studied cards
/// keep coming back on their SM-2 schedule regardless. See
/// `LexemePool.sessionLexemes` for where the filter is applied.
public enum LexemeLevel: String, Codable, Hashable, CaseIterable, Sendable {
    case a1, a2, b1, b2, c1

    /// 1-based frequency rank range. `c1` is open-ended on the high end so
    /// any far-tail entry has a level even if the catalog later expands.
    public var rankRange: ClosedRange<Int> {
        switch self {
        case .a1: return 1...250
        case .a2: return 251...500
        case .b1: return 501...1000
        case .b2: return 1001...2000
        case .c1: return 2001...Int.max
        }
    }

    public var displayName: String {
        switch self {
        case .a1: return "A1 — Beginner"
        case .a2: return "A2 — Elementary"
        case .b1: return "B1 — Intermediate"
        case .b2: return "B2 — Upper-intermediate"
        case .c1: return "C1+ — Advanced"
        }
    }

    /// The level containing this frequency rank. Rank 0 (unranked) falls
    /// into `c1` — better to include unknown-rank lexemes when only the
    /// top end is on than silently drop them.
    public static func level(forRank rank: Int) -> LexemeLevel {
        guard rank > 0 else { return .c1 }
        for level in LexemeLevel.allCases where level.rankRange.contains(rank) {
            return level
        }
        return .c1
    }
}
