import Foundation
import SharedModels

/// Loads and queries the curated reflexive-verb list bundled with the app
/// (Gitea issue #28). One JSON load at init; in-memory lookup thereafter.
///
/// `entries(for:)` returns a list because a single base infinitive may map to
/// multiple reflexive entries — e.g., `ponerse` covers both "to put on
/// (clothing) / to become" and "to come to an agreement (with)".
@MainActor
@Observable
final class ReflexiveVerbStore {

    /// Process-wide accessor for services that can't use @Environment injection
    /// (e.g. PracticeSessionService called from ViewModels). Views should still
    /// prefer @Environment(ReflexiveVerbStore.self) for consistency.
    static let shared = ReflexiveVerbStore()

    private(set) var entries: [ReflexiveVerb] = []
    private var indexByBase: [String: [ReflexiveVerb]] = [:]

    /// Set of base infinitives present in the list. Cheap lookup for filters.
    private(set) var baseInfinitives: Set<String> = []

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

    /// All reflexive entries whose base infinitive matches (case-insensitive).
    func entries(for baseInfinitive: String) -> [ReflexiveVerb] {
        indexByBase[baseInfinitive.lowercased()] ?? []
    }

    /// Convenience — true when the verb's bare infinitive appears in the list.
    func isReflexive(baseInfinitive: String) -> Bool {
        baseInfinitives.contains(baseInfinitive.lowercased())
    }

    private func load(from bundle: Bundle) {
        guard let url = bundle.url(forResource: "reflexive_verbs", withExtension: "json"),
              let data = try? Data(contentsOf: url) else {
            print("[ReflexiveVerbStore] bundled reflexive_verbs.json not found")
            return
        }
        do {
            let decoded = try JSONDecoder().decode([ReflexiveVerb].self, from: data)
            entries = decoded
            var index: [String: [ReflexiveVerb]] = [:]
            for entry in decoded {
                index[entry.baseInfinitive.lowercased(), default: []].append(entry)
            }
            indexByBase = index
            baseInfinitives = Set(index.keys)
            print("[ReflexiveVerbStore] loaded \(decoded.count) entries (\(baseInfinitives.count) distinct base infinitives)")
        } catch {
            print("[ReflexiveVerbStore] decode failed: \(error)")
        }
    }
}
