import Foundation

/// Syncs card data to watchOS via shared App Group UserDefaults
struct WatchSyncService {
    private static let appGroupID = "group.com.mbrucedogs.BusinessCard"
    private static let cardsKey = "SyncedCards"
    
    private static var sharedDefaults: UserDefaults? {
        UserDefaults(suiteName: appGroupID)
    }
    
    /// Syncs the given cards to the shared App Group for watchOS to read
    @MainActor
    static func syncCards(_ cards: [BusinessCard]) {
        guard let defaults = sharedDefaults else { return }
        
        let syncableCards = cards.map { card in
            // Get first email, phone, website, location from contact fields
            let email = card.firstContactField(ofType: "email")?.value ?? ""
            let phone = card.firstContactField(ofType: "phone")?.value ?? ""
            let website = card.firstContactField(ofType: "website")?.value ?? ""
            let linkedIn = card.firstContactField(ofType: "linkedIn")?.value ?? ""
            let twitter = card.firstContactField(ofType: "twitter")?.value ?? ""
            let instagram = card.firstContactField(ofType: "instagram")?.value ?? ""
            
            // Format address for display (decode from stored JSON/legacy format)
            let addressValue = card.firstContactField(ofType: "address")?.value ?? ""
            let location = PostalAddress.decode(from: addressValue)?.singleLineString ?? addressValue
            
            return SyncableCard(
                id: card.id,
                displayName: card.displayName,
                role: card.role,
                company: card.company,
                email: email,
                phone: phone,
                website: website,
                location: location,
                isDefault: card.isDefault,
                pronouns: card.pronouns,
                bio: card.bio,
                linkedIn: linkedIn,
                twitter: twitter,
                instagram: instagram
            )
        }
        
        if let encoded = try? JSONEncoder().encode(syncableCards) {
            defaults.set(encoded, forKey: cardsKey)
        }
    }
}

/// A simplified card structure that can be shared between iOS and watchOS
struct SyncableCard: Codable, Identifiable {
    let id: UUID
    var displayName: String
    var role: String
    var company: String
    var email: String
    var phone: String
    var website: String
    var location: String
    var isDefault: Bool
    var pronouns: String
    var bio: String
    var linkedIn: String
    var twitter: String
    var instagram: String
    
    var vCardPayload: String {
        var lines = [
            "BEGIN:VCARD",
            "VERSION:3.0",
            "FN:\(displayName)",
            "ORG:\(company)",
            "TITLE:\(role)"
        ]
        
        if !phone.isEmpty {
            lines.append("TEL;TYPE=work:\(phone)")
        }
        if !email.isEmpty {
            lines.append("EMAIL;TYPE=work:\(email)")
        }
        if !website.isEmpty {
            lines.append("URL:\(website)")
        }
        if !location.isEmpty {
            lines.append("ADR;TYPE=work:;;\(location)")
        }
        if !bio.isEmpty {
            lines.append("NOTE:\(bio)")
        }
        if !linkedIn.isEmpty {
            lines.append("X-SOCIALPROFILE;TYPE=linkedin:\(linkedIn)")
        }
        if !twitter.isEmpty {
            lines.append("X-SOCIALPROFILE;TYPE=twitter:\(twitter)")
        }
        if !instagram.isEmpty {
            lines.append("X-SOCIALPROFILE;TYPE=instagram:\(instagram)")
        }
        
        lines.append("END:VCARD")
        return lines.joined(separator: "\n")
    }
}
