import Foundation

#if canImport(Darwin)
import Darwin

/// Best-effort primary LAN IPv4 of this Mac, embedded in the pairing QR so the phone can dial
/// the host directly (SYNC §4.2 LAN hint) without relying on Bonjour discovery — far more
/// robust on real networks. Prefers Wi‑Fi/Ethernet (`en*`), skips loopback and link-local.
public enum LANAddress {
    public static func primaryIPv4() -> String? {
        var head: UnsafeMutablePointer<ifaddrs>?
        guard getifaddrs(&head) == 0, let first = head else { return nil }
        defer { freeifaddrs(head) }

        var best: String?
        for ptr in sequence(first: first, next: { $0.pointee.ifa_next }) {
            let flags = Int32(ptr.pointee.ifa_flags)
            guard flags & IFF_UP == IFF_UP, flags & IFF_LOOPBACK == 0 else { continue }
            guard let addr = ptr.pointee.ifa_addr, addr.pointee.sa_family == sa_family_t(AF_INET)
            else { continue }
            let name = String(cString: ptr.pointee.ifa_name)

            var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
            guard getnameinfo(
                addr, socklen_t(addr.pointee.sa_len), &host, socklen_t(host.count),
                nil, 0, NI_NUMERICHOST) == 0 else { continue }
            let ip = String(decoding: host.prefix(while: { $0 != 0 }).map { UInt8(bitPattern: $0) }, as: UTF8.self)
            if ip.hasPrefix("169.254.") { continue }  // link-local, not routable

            if name.hasPrefix("en") { return ip }     // Wi‑Fi/Ethernet — take immediately
            if best == nil { best = ip }              // otherwise remember a fallback
        }
        return best
    }
}
#endif
