import Foundation
import Security
import NucleicProtocol

/// 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
    }
}
