import Foundation
import NucleicProtocol

/// Persists the host's long-term `DeviceIdentity` (SYNC §4.1) in the platform secret store —
/// the data-protection Keychain on macOS (see ``KeychainOwnedAccess``), the 0600-file store on
/// a Linux runner (part of the runner's checkpointed state, CLOUD_RUNTIME §3.5). Generated
/// once and reused, so paired devices keep recognizing this host across launches/restarts.
public enum HostIdentityStore {
    private static let account = "com.nucleic.host.identity"

    public static func loadOrCreate() -> DeviceIdentity {
        if let data = SecretStores.default.get(service: nil, account: account),
           let identity = try? DeviceIdentity(importingRaw: data) {
            return identity
        }
        let identity = DeviceIdentity()
        SecretStores.default.set(service: nil, account: account, data: identity.exportRaw())
        return identity
    }

    /// Drop the stored identity so the next `loadOrCreate()` mints a fresh keypair/`hostID` —
    /// the "reset Covalence" path. Every device paired against the old identity stops matching its
    /// pin regardless (the reset also forgets the pairings), so this is safe to call standalone.
    public static func reset() {
        SecretStores.default.remove(service: nil, account: account)
    }
}
