import Foundation

enum ServerEnvironment: String, CaseIterable, Identifiable {
    case production
    case local

    var id: String { rawValue }

    var title: String {
        switch self {
        case .production: return "生产服务器"
        case .local: return "本地服务器"
        }
    }

    var subtitle: String {
        switch self {
        case .production: return "w.tkmind.cn"
        case .local: return "开发机前后端 (18003/18004)"
        }
    }

    var defaultBaseURL: String {
        switch self {
        case .production: return "https://w.tkmind.cn"
        case .local: return "http://127.0.0.1:18003"
        }
    }

    var iconName: String {
        switch self {
        case .production: return "cloud.fill"
        case .local: return "laptopcomputer"
        }
    }
}

enum ServerSettings {
    private static let environmentKey = "wordloop.server.environment"
    private static let localBaseURLKey = "wordloop.server.localBaseURL"

    static var environment: ServerEnvironment {
        get {
            guard let raw = UserDefaults.standard.string(forKey: environmentKey),
                  let env = ServerEnvironment(rawValue: raw) else {
                return .production
            }
            return env
        }
        set {
            UserDefaults.standard.set(newValue.rawValue, forKey: environmentKey)
        }
    }

    static var localBaseURL: String {
        get {
            UserDefaults.standard.string(forKey: localBaseURLKey)
                ?? ServerEnvironment.local.defaultBaseURL
        }
        set {
            UserDefaults.standard.set(newValue.trimmingCharacters(in: .whitespacesAndNewlines),
                                      forKey: localBaseURLKey)
        }
    }

    static var activeBaseURL: String {
        switch environment {
        case .production:
            return ServerEnvironment.production.defaultBaseURL
        case .local:
            return normalizedBaseURL(localBaseURL)
        }
    }

    static var activeAPIBaseURL: String {
        apiBaseURL(for: activeBaseURL)
    }

    static func apiBaseURL(for webBaseURL: String) -> String {
        let normalized = normalizedBaseURL(webBaseURL)
        if normalized.contains(":18003") {
            return normalized.replacingOccurrences(of: ":18003", with: ":18004") + "/api"
        }
        return normalized + "/api"
    }

    static var bundledWWWDirectory: URL? {
        if let url = Bundle.main.url(forResource: "www", withExtension: nil) {
            return url
        }
        let fallback = Bundle.main.bundleURL.appendingPathComponent("www", isDirectory: true)
        return FileManager.default.fileExists(atPath: fallback.path) ? fallback : nil
    }

    static var bundledHomeURL: URL? {
        bundledWWWDirectory?.appendingPathComponent("index.html")
    }

    static func bundledReadAccessURL() -> URL? {
        bundledWWWDirectory ?? Bundle.main.bundleURL
    }

    static func homeURL(for baseURL: String) -> URL? {
        bundledHomeURL ?? {
            let trimmed = normalizedBaseURL(baseURL)
            return URL(string: "\(trimmed)/")
        }()
    }

    static func loginURL(for baseURL: String) -> URL? {
        if bundledHomeURL != nil {
            return bundledHomeURL
        }
        let trimmed = normalizedBaseURL(baseURL)
        return URL(string: "\(trimmed)/login")
    }

    static func normalizedBaseURL(_ value: String) -> String {
        var url = value.trimmingCharacters(in: .whitespacesAndNewlines)
        while url.hasSuffix("/") {
            url.removeLast()
        }
        return url
    }
}
