import Foundation

/// Centralized app identifiers that read from Info.plist (which gets values from xcconfig).
///
/// The source of truth is `Configuration/Base.xcconfig`. Values flow:
/// Base.xcconfig → Info.plist → AppIdentifiers (Swift)
///
/// When migrating to a new developer account:
/// 1. Update `COMPANY_IDENTIFIER` and `DEVELOPMENT_TEAM` in Base.xcconfig
/// 2. The entitlements, bundle IDs, and Swift code all update automatically
/// 3. See DevAccount-Migration.md for complete checklist
enum AppIdentifiers {

    // MARK: - Runtime Identifiers (read from Info.plist)

    /// Public app name for user-facing UI text.
    static let publicAppName: String = {
        (Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String)
            ?? (Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String)
            ?? "App"
    }()

    /// App Group identifier for sharing data between app and extensions.
    static let appGroupIdentifier: String = {
        Bundle.main.object(forInfoDictionaryKey: "AppGroupIdentifier") as? String
            ?? "group.com.mbrucedogs.BusinessCard"
    }()

    /// CloudKit container identifier.
    static let cloudKitContainerIdentifier: String = {
        Bundle.main.object(forInfoDictionaryKey: "CloudKitContainerIdentifier") as? String
            ?? "iCloud.com.mbrucedogs.BusinessCard"
    }()
    
    /// Whether CloudKit-backed SwiftData sync should be enabled.
    /// Defaults to false so local persistence works even when CloudKit model constraints are unmet.
    static let isCloudKitSyncEnabled: Bool = {
        let rawValue = (Bundle.main.object(forInfoDictionaryKey: "CloudKitSyncEnabled") as? String) ?? "NO"
        return NSString(string: rawValue).boolValue
    }()

    /// App Clip domain for sharing URLs.
    static let appClipDomain: String = {
        Bundle.main.object(forInfoDictionaryKey: "AppClipDomain") as? String
            ?? "topdoglabs.com"
    }()

    // MARK: - Derived Identifiers

    /// Bundle identifier of the main app.
    static var bundleIdentifier: String {
        Bundle.main.bundleIdentifier ?? "com.mbrucedogs.BusinessCard"
    }

    /// Watch app bundle identifier (derived from main app).
    static var watchBundleIdentifier: String {
        "\(bundleIdentifier).watchkitapp"
    }

    /// App Clip bundle identifier (derived from main app).
    static var appClipBundleIdentifier: String {
        "\(bundleIdentifier).Clip"
    }

    // MARK: - App Clip URL Generation

    /// Generates an App Clip invocation URL for a shared card record.
    static func appClipURL(recordName: String) -> URL? {
        URL(string: "https://\(appClipDomain)/appclip/businesscard?id=\(recordName)")
    }
}
