import Foundation
import Security

/// Secure store for the user-supplied Anthropic API key used by Nucleic Control container
/// sessions when `ContainerServiceSettings.controlAuthMode == .apiKey`. Backed by the macOS
/// Keychain (a generic-password item Nucleic owns), so the secret never lands in UserDefaults,
/// a plist, or a command line. All operations are best-effort and synchronous.
public enum ControlAPIKeyStore {
    private static let service = "Nucleic Control API Key"
    private static let account = "anthropic"

    private static var baseQuery: [String: Any] {
        [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
        ]
    }

    /// The stored API key, or nil if none is set (or what's stored is blank).
    public static func load() -> String? {
        var query = baseQuery
        query[kSecReturnData as String] = true
        query[kSecMatchLimit as String] = kSecMatchLimitOne
        var item: CFTypeRef?
        guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
              let data = item as? Data,
              let key = String(data: data, encoding: .utf8),
              !key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
        else { return nil }
        return key
    }

    /// Whether a (non-blank) API key is currently stored.
    public static var hasKey: Bool { load() != nil }

    /// Store (or replace) the API key. A blank value clears it instead. Returns whether the
    /// Keychain ended in the intended state.
    @discardableResult
    public static func save(_ key: String) -> Bool {
        let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return clear() }
        let data = Data(trimmed.utf8)
        let update = SecItemUpdate(baseQuery as CFDictionary,
                                   [kSecValueData as String: data] as CFDictionary)
        if update == errSecSuccess { return true }
        guard update == errSecItemNotFound else { return false }
        var add = baseQuery
        add[kSecValueData as String] = data
        add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
        return SecItemAdd(add as CFDictionary, nil) == errSecSuccess
    }

    /// Remove the stored API key. Succeeds whether or not one was present.
    @discardableResult
    public static func clear() -> Bool {
        let status = SecItemDelete(baseQuery as CFDictionary)
        return status == errSecSuccess || status == errSecItemNotFound
    }
}
