import Foundation

enum WordStoreError: Error, LocalizedError {
    case fileNotFound
    case decodingFailed(Error)

    var errorDescription: String? {
        switch self {
        case .fileNotFound: return "词库文件缺失"
        case .decodingFailed(let error): return "词库解析失败：\(error.localizedDescription)"
        }
    }
}

@Observable
final class WordStore {
    private(set) var bank: WordBank?
    private(set) var loadError: String?

    var categories: [WordCategory] { bank?.categories ?? [] }

    func load() {
        guard bank == nil, loadError == nil else { return }
        guard let url = Bundle.main.url(forResource: "words", withExtension: "json") else {
            loadError = WordStoreError.fileNotFound.localizedDescription
            return
        }
        do {
            let data = try Data(contentsOf: url)
            bank = try JSONDecoder().decode(WordBank.self, from: data)
        } catch {
            loadError = WordStoreError.decodingFailed(error).localizedDescription
        }
    }
}
