import Foundation
import NucleicProtocol

#if canImport(Security)
import Security

/// Persists the Mac host's long-term `DeviceIdentity` in the data-protection Keychain (SYNC §4.1).
/// Generated once and reused, so paired iPhones keep recognizing this Mac across launches. Access is
/// governed by Nucleic's Keychain access group, so the app reads it back silently — see
/// ``KeychainOwnedAccess``.
public enum HostIdentityStore {
    private static let account = "com.nucleic.host.identity"

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

    public static func loadOrCreate() -> DeviceIdentity {
        if let data = KeychainOwnedAccess.copyData(identity),
           let identity = try? DeviceIdentity(importingRaw: data) {
            return identity
        }
        let identity = DeviceIdentity()
        var add = Self.identity
        add[kSecValueData as String] = identity.exportRaw()
        KeychainOwnedAccess.set(add)
        return identity
    }
}
#else

/// Linux (runner) variant: the host identity lives in the 0600-file secret store — the
/// CLOUD_RUNTIME §3.1 Keychain seam. Same contract: generated once, reused forever, so paired
/// devices keep recognizing this runner across container restarts (the secrets dir is part of
/// the runner's checkpointed state, CLOUD_RUNTIME §3.5).
public enum HostIdentityStore {
    private static let account = "com.nucleic.host.identity"

    public static func loadOrCreate() -> DeviceIdentity {
        if let data = LinuxSecretStore.read(account: account),
           let identity = try? DeviceIdentity(importingRaw: data) {
            return identity
        }
        let identity = DeviceIdentity()
        LinuxSecretStore.write(account: account, data: identity.exportRaw())
        return identity
    }
}
#endif
