DomainDig/DomainViewModel.swift

36ea668d7fc9070770973b0bc329f4319bf43cab
domain-dig/DomainDig/DomainViewModel.swift history · blame · raw

2658 lines · 103457 bytes

   1import Foundation
   2import SwiftUI
   3
   4enum ResultTone {
   5    case primary
   6    case secondary
   7    case success
   8    case warning
   9    case failure
  10}
  11
  12struct SummaryFieldViewData: Identifiable {
  13    let id = UUID()
  14    let label: String
  15    let value: String
  16    let tone: ResultTone
  17}
  18
  19struct InfoRowViewData: Identifiable {
  20    let id = UUID()
  21    let label: String
  22    let value: String
  23    let tone: ResultTone
  24}
  25
  26struct SectionMessageViewData {
  27    let text: String
  28    let isError: Bool
  29}
  30
  31struct DNSRecordSectionViewData: Identifiable {
  32    let id = UUID()
  33    let title: String
  34    let rows: [InfoRowViewData]
  35    let wildcardRows: [InfoRowViewData]
  36    let wildcardTitle: String?
  37    let message: SectionMessageViewData?
  38}
  39
  40struct EmailRowViewData: Identifiable {
  41    let id = UUID()
  42    let label: String
  43    let status: String
  44    let statusTone: ResultTone
  45    let detail: String
  46    let auxiliaryDetail: String?
  47}
  48
  49struct RedirectHopViewData: Identifiable {
  50    let id = UUID()
  51    let stepLabel: String
  52    let statusCode: String
  53    let url: String
  54    let isFinal: Bool
  55}
  56
  57struct ReachabilityRowViewData: Identifiable {
  58    let id = UUID()
  59    let portLabel: String
  60    let latencyLabel: String
  61    let statusLabel: String
  62    let statusTone: ResultTone
  63}
  64
  65struct PortScanRowViewData: Identifiable {
  66    let id = UUID()
  67    let portLabel: String
  68    let service: String
  69    let statusLabel: String
  70    let statusTone: ResultTone
  71    let banner: String?
  72    let durationLabel: String?
  73}
  74
  75struct SubdomainRowViewData: Identifiable {
  76    let id: String
  77    let hostname: String
  78    let isInteresting: Bool
  79
  80    init(hostname: String, isInteresting: Bool) {
  81        self.id = hostname
  82        self.hostname = hostname
  83        self.isInteresting = isInteresting
  84    }
  85}
  86
  87struct DomainSuggestionViewData: Identifiable {
  88    let id: UUID
  89    let domain: String
  90    let status: String
  91    let tone: ResultTone
  92}
  93
  94private struct BatchLookupPayload {
  95    let snapshot: LookupSnapshot
  96}
  97
  98@MainActor
  99@Observable
 100final class DomainViewModel {
 101    var domain: String = ""
 102    var bulkInput: String = ""
 103
 104    var dnsSections: [DNSSection] = []
 105    var dnsLoading = false
 106    var dnsError: String?
 107    var availabilityResult: DomainAvailabilityResult?
 108    var availabilityLoading = false
 109    var suggestions: [DomainSuggestionResult] = []
 110    var suggestionsLoading = false
 111
 112    var sslInfo: SSLCertificateInfo?
 113    var sslLoading = false
 114    var sslError: String?
 115    var hstsPreloaded: Bool?
 116    var hstsLoading = false
 117
 118    var httpHeaders: [HTTPHeader] = []
 119    var httpSecurityGrade: String?
 120    var httpStatusCode: Int?
 121    var httpResponseTimeMs: Int?
 122    var httpProtocol: String?
 123    var http3Advertised = false
 124    var httpHeadersLoading = false
 125    var httpHeadersError: String?
 126
 127    var reachabilityResults: [PortReachability] = []
 128    var reachabilityLoading = false
 129    var reachabilityError: String?
 130
 131    var ipGeolocation: IPGeolocation?
 132    var ipGeolocationLoading = false
 133    var ipGeolocationError: String?
 134
 135    var emailSecurity: EmailSecurityResult?
 136    var emailSecurityLoading = false
 137    var emailSecurityError: String?
 138
 139    var ownershipResult: DomainOwnership?
 140    var ownershipLoading = false
 141    var ownershipError: String?
 142
 143    var ptrRecord: String?
 144    var ptrLoading = false
 145    var ptrError: String?
 146
 147    var redirectChain: [RedirectHop] = []
 148    var redirectChainLoading = false
 149    var redirectChainError: String?
 150
 151    var subdomains: [DiscoveredSubdomain] = []
 152    var subdomainsLoading = false
 153    var subdomainsError: String?
 154
 155    var portScanResults: [PortScanResult] = []
 156    var portScanLoading = false
 157    var portScanError: String?
 158    var customPortResults: [PortScanResult] = []
 159    var customPortScanLoading = false
 160    var customPortScanError: String?
 161
 162    var hasRun = false
 163    private(set) var searchedDomain: String = ""
 164    private(set) var lastLookupDurationMs: Int?
 165    private(set) var currentDiffSections: [DomainDiffSection] = []
 166    private(set) var currentChangeSummary: DomainChangeSummary?
 167    private(set) var ownershipDiff: [DomainDiffItem] = []
 168    private(set) var refreshingTrackedDomainID: UUID?
 169    private(set) var rerunNavigationToken = UUID()
 170    private(set) var batchResults: [BatchLookupResult] = []
 171    private(set) var batchLookupSource: BatchLookupSource = .manual
 172    private(set) var batchCurrentDomain: String?
 173    private(set) var batchCompletedCount = 0
 174    private(set) var batchTotalCount = 0
 175    private(set) var batchLookupRunning = false
 176    var latestBatchSweepSummary: BatchSweepSummary?
 177    private(set) var notificationsAuthorized = false
 178
 179    private var lookupTask: Task<Void, Never>?
 180    private var customPortScanTask: Task<Void, Never>?
 181    private var batchTask: Task<Void, Never>?
 182    private var activeLookupID = UUID()
 183    private var lookupStartedAt: Date?
 184    private var activeBatchDomains: [String] = []
 185    private var lastBatchStartedAt: Date?
 186    private let reportBuilder = DomainReportBuilder()
 187    private let inspectionService = DomainInspectionService()
 188    private(set) var currentResultSource: LookupResultSource = .live
 189    private(set) var currentCachedSections: [LookupSectionKind] = []
 190    private(set) var currentStatusMessage: String?
 191    private(set) var currentSnapshotTimestamp = Date()
 192    private(set) var currentHistoryEntryID: UUID?
 193
 194    private static let recentSearchesKey = "recentSearches"
 195    private static let maxRecent = 20
 196    var recentSearches: [String] = UserDefaults.standard.stringArray(forKey: recentSearchesKey) ?? []
 197
 198    private static let savedDomainsKey = "savedDomains"
 199    var savedDomains: [String] = UserDefaults.standard.stringArray(forKey: savedDomainsKey) ?? []
 200
 201    private static let trackedDomainsKey = "trackedDomains"
 202    private static let legacyWatchedDomainsKey = "watchedDomains"
 203    var trackedDomains: [TrackedDomain] = DomainViewModel.loadTrackedDomains()
 204
 205    private static let historyKey = "lookupHistory"
 206    private static let maxHistory = 250
 207    var history: [HistoryEntry] = {
 208        guard let data = UserDefaults.standard.data(forKey: historyKey),
 209              let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) else {
 210            return []
 211        }
 212        return entries
 213    }()
 214    var historySearchText = ""
 215    var historyDateFilter: HistoryDateFilter = .all
 216    var historyChangeFilter: ChangeFilterOption = .all
 217    var historySortOption: HistorySortOption = .newest
 218    var watchlistSearchText = ""
 219    var watchlistFilter: WatchlistFilterOption = .all
 220    var watchlistSortOption: WatchlistSortOption = .pinned
 221
 222    var trimmedDomain: String {
 223        domain
 224            .trimmingCharacters(in: .whitespacesAndNewlines)
 225            .replacingOccurrences(of: "https://", with: "")
 226            .replacingOccurrences(of: "http://", with: "")
 227            .components(separatedBy: "/").first ?? ""
 228    }
 229
 230    var resultsLoaded: Bool {
 231        hasRun &&
 232            !dnsLoading &&
 233            !availabilityLoading &&
 234            !suggestionsLoading &&
 235            !sslLoading &&
 236            !hstsLoading &&
 237            !httpHeadersLoading &&
 238            !reachabilityLoading &&
 239            !ipGeolocationLoading &&
 240            !emailSecurityLoading &&
 241            !ownershipLoading &&
 242            !ptrLoading &&
 243            !redirectChainLoading &&
 244            !subdomainsLoading &&
 245            !portScanLoading &&
 246            !customPortScanLoading
 247    }
 248
 249    var isCloudflareProxied: Bool {
 250        httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
 251    }
 252
 253    var isCurrentDomainSaved: Bool {
 254        !searchedDomain.isEmpty && savedDomains.contains(where: { $0.lowercased() == searchedDomain.lowercased() })
 255    }
 256
 257    var sortedTrackedDomains: [TrackedDomain] {
 258        sortedTrackedDomains(from: trackedDomains, using: .pinned)
 259    }
 260
 261    var filteredHistory: [HistoryEntry] {
 262        let calendar = Calendar.current
 263        let now = Date()
 264        let query = historySearchText.trimmingCharacters(in: .whitespacesAndNewlines)
 265
 266        return history
 267            .lazy
 268            .filter { entry in
 269                query.isEmpty || entry.domain.localizedCaseInsensitiveContains(query)
 270            }
 271            .filter { entry in
 272                switch self.historyDateFilter {
 273                case .today:
 274                    return calendar.isDate(entry.timestamp, inSameDayAs: now)
 275                case .last7Days:
 276                    guard let startDate = calendar.date(byAdding: .day, value: -7, to: now) else { return true }
 277                    return entry.timestamp >= startDate
 278                case .all:
 279                    return true
 280                }
 281            }
 282            .filter { entry in
 283                switch self.historyChangeFilter {
 284                case .all:
 285                    return true
 286                case .changed:
 287                    return entry.changeSummary?.hasChanges == true
 288                case .unchanged:
 289                    return entry.changeSummary?.hasChanges != true
 290                }
 291            }
 292            .sorted(by: historySortPredicate)
 293    }
 294
 295    var filteredTrackedDomains: [TrackedDomain] {
 296        let query = watchlistSearchText.trimmingCharacters(in: .whitespacesAndNewlines)
 297        let filtered = trackedDomains.filter { trackedDomain in
 298            if !query.isEmpty, !trackedDomain.domain.localizedCaseInsensitiveContains(query) {
 299                return false
 300            }
 301
 302            switch watchlistFilter {
 303            case .all:
 304                return true
 305            case .pinnedOnly:
 306                return trackedDomain.isPinned
 307            case .changedOnly:
 308                return trackedDomain.lastChangeSummary?.hasChanges == true
 309            }
 310        }
 311
 312        return sortedTrackedDomains(from: filtered, using: watchlistSortOption)
 313    }
 314
 315    var batchProgressLabel: String {
 316        guard batchTotalCount > 0 else { return "No active batch" }
 317        let domainLabel = activeBatchDomains.first ?? batchCurrentDomain ?? "Preparing"
 318        return "\(batchCompletedCount)/\(batchTotalCount) • \(domainLabel)"
 319    }
 320
 321    var currentBatchResultEntries: [HistoryEntry] {
 322        batchResults.compactMap { result in
 323            guard let historyEntryID = result.historyEntryID else { return nil }
 324            return history.first(where: { $0.id == historyEntryID })
 325        }
 326    }
 327
 328    var currentTrackedDomain: TrackedDomain? {
 329        guard !searchedDomain.isEmpty else { return nil }
 330        return trackedDomain(for: searchedDomain)
 331    }
 332
 333    var isCurrentDomainTracked: Bool {
 334        currentTrackedDomain != nil
 335    }
 336
 337    var trackingLimitMessage: String? {
 338        nil
 339    }
 340
 341    var canTrackCurrentDomain: Bool {
 342        true
 343    }
 344
 345    var resolverDisplayName: String {
 346        DNSLookupService.currentResolverDisplayName()
 347    }
 348
 349    var resolverURLString: String {
 350        DNSLookupService.currentResolverURLString()
 351    }
 352
 353    var allPortScanResults: [PortScanResult] {
 354        (portScanResults + customPortResults).sorted {
 355            if $0.kind == $1.kind {
 356                return $0.port < $1.port
 357            }
 358            return $0.kind == .standard
 359        }
 360    }
 361
 362    var currentSnapshot: LookupSnapshot {
 363        LookupSnapshot(
 364            historyEntryID: currentHistoryEntryID,
 365            domain: searchedDomain,
 366            timestamp: currentSnapshotTimestamp,
 367            trackedDomainID: currentTrackedDomain?.id,
 368            resolverDisplayName: resolverDisplayName,
 369            resolverURLString: resolverURLString,
 370            totalLookupDurationMs: lastLookupDurationMs,
 371            dnsSections: dnsSections,
 372            dnsError: dnsError,
 373            availabilityResult: availabilityResult,
 374            suggestions: suggestions,
 375            sslInfo: sslInfo,
 376            sslError: sslError,
 377            hstsPreloaded: hstsPreloaded,
 378            httpHeaders: httpHeaders,
 379            httpSecurityGrade: httpSecurityGrade,
 380            httpStatusCode: httpStatusCode,
 381            httpResponseTimeMs: httpResponseTimeMs,
 382            httpProtocol: httpProtocol,
 383            http3Advertised: http3Advertised,
 384            httpHeadersError: httpHeadersError,
 385            reachabilityResults: reachabilityResults,
 386            reachabilityError: reachabilityError,
 387            ipGeolocation: ipGeolocation,
 388            ipGeolocationError: ipGeolocationError,
 389            emailSecurity: emailSecurity,
 390            emailSecurityError: emailSecurityError,
 391            ownership: ownershipResult,
 392            ownershipError: ownershipError,
 393            ptrRecord: ptrRecord,
 394            ptrError: ptrError,
 395            redirectChain: redirectChain,
 396            redirectChainError: redirectChainError,
 397            subdomains: subdomains,
 398            subdomainsError: subdomainsError,
 399            portScanResults: allPortScanResults,
 400            portScanError: combinedPortScanError,
 401            changeSummary: currentChangeSummary,
 402            resultSource: currentResultSource,
 403            cachedSections: currentCachedSections,
 404            statusMessage: currentStatusMessage
 405        )
 406    }
 407
 408    var currentReport: DomainReport? {
 409        guard !searchedDomain.isEmpty else { return nil }
 410        return reportBuilder.build(
 411            from: currentSnapshot,
 412            previousSnapshot: previousSnapshot(
 413                for: searchedDomain,
 414                trackedDomainID: currentTrackedDomain?.id,
 415                replacingLatest: false
 416            )
 417        )
 418    }
 419
 420    var summaryFields: [SummaryFieldViewData] {
 421        Self.summaryFields(from: currentSnapshot)
 422    }
 423
 424    var domainRows: [InfoRowViewData] {
 425        Self.domainRows(from: currentSnapshot)
 426    }
 427
 428    var dnsRows: [DNSRecordSectionViewData] {
 429        Self.dnsRows(from: currentSnapshot)
 430    }
 431
 432    var suggestionRows: [DomainSuggestionViewData] {
 433        Self.suggestionRows(from: currentSnapshot)
 434    }
 435
 436    var dnssecLabel: String? {
 437        Self.dnssecLabel(from: currentSnapshot)
 438    }
 439
 440    var ptrMessage: SectionMessageViewData? {
 441        Self.ptrMessage(from: currentSnapshot)
 442    }
 443
 444    var webCertificateRows: [InfoRowViewData] {
 445        Self.webCertificateRows(from: currentSnapshot)
 446    }
 447
 448    var webResponseRows: [InfoRowViewData] {
 449        Self.webResponseRows(from: currentSnapshot)
 450    }
 451
 452    var redirectRows: [RedirectHopViewData] {
 453        Self.redirectRows(from: currentSnapshot)
 454    }
 455
 456    var emailRows: [EmailRowViewData] {
 457        Self.emailRows(from: currentSnapshot)
 458    }
 459
 460    var ownershipRows: [InfoRowViewData] {
 461        Self.ownershipRows(from: currentSnapshot)
 462    }
 463
 464    var subdomainRows: [SubdomainRowViewData] {
 465        Self.subdomainRows(from: currentSnapshot)
 466    }
 467
 468    var reachabilityRows: [ReachabilityRowViewData] {
 469        Self.reachabilityRows(from: currentSnapshot)
 470    }
 471
 472    var locationRows: [InfoRowViewData] {
 473        Self.locationRows(from: currentSnapshot)
 474    }
 475
 476    var standardPortRows: [PortScanRowViewData] {
 477        Self.portRows(from: currentSnapshot, kind: .standard)
 478    }
 479
 480    var customPortRows: [PortScanRowViewData] {
 481        Self.portRows(from: currentSnapshot, kind: .custom)
 482    }
 483
 484    var combinedPortScanError: String? {
 485        [portScanError, customPortScanError].compactMap { $0 }.joined(separator: "\n").nilIfEmpty
 486    }
 487
 488    func toggleSavedDomain() {
 489        if isCurrentDomainSaved {
 490            savedDomains.removeAll { $0.lowercased() == searchedDomain.lowercased() }
 491        } else {
 492            savedDomains.append(searchedDomain)
 493        }
 494        UserDefaults.standard.set(savedDomains, forKey: Self.savedDomainsKey)
 495    }
 496
 497    func removeSavedDomains(at offsets: IndexSet) {
 498        savedDomains.remove(atOffsets: offsets)
 499        UserDefaults.standard.set(savedDomains, forKey: Self.savedDomainsKey)
 500    }
 501
 502    @discardableResult
 503    func trackCurrentDomain() -> Bool {
 504        guard !searchedDomain.isEmpty else { return false }
 505        return trackDomain(domain: searchedDomain, availabilityStatus: availabilityResult?.status)
 506    }
 507
 508    @discardableResult
 509    func trackDomain(domain: String, availabilityStatus: DomainAvailabilityStatus?) -> Bool {
 510        let normalizedDomain = normalizedDomain(domain)
 511        guard !normalizedDomain.isEmpty else { return false }
 512
 513        if trackedDomain(for: normalizedDomain) != nil {
 514            return true
 515        }
 516
 517        guard PremiumAccessService.canAddTrackedDomain(currentCount: trackedDomains.count) else {
 518            return false
 519        }
 520
 521        trackedDomains.insert(
 522            TrackedDomain(
 523                domain: normalizedDomain,
 524                createdAt: Date(),
 525                updatedAt: Date(),
 526                lastKnownAvailability: availabilityStatus
 527            ),
 528            at: 0
 529        )
 530        persistTrackedDomains()
 531        linkTrackedDomainHistory(for: normalizedDomain)
 532        return true
 533    }
 534
 535    func refreshTrackedDomain(_ trackedDomain: TrackedDomain) {
 536        refreshingTrackedDomainID = trackedDomain.id
 537        domain = trackedDomain.domain
 538        Task { [weak self] in
 539            guard let self else { return }
 540            self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
 541        }
 542        run()
 543    }
 544
 545    func rerunInspection(for trackedDomain: TrackedDomain) {
 546        domain = trackedDomain.domain
 547        run()
 548        rerunNavigationToken = UUID()
 549    }
 550
 551    func deleteTrackedDomains(at offsets: IndexSet) {
 552        let ids = offsets.map { sortedTrackedDomains[$0].id }
 553        trackedDomains.removeAll { ids.contains($0.id) }
 554        history.indices.forEach { index in
 555            if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) {
 556                history[index].trackedDomainID = nil
 557            }
 558        }
 559        persistTrackedDomains()
 560        persistHistory()
 561    }
 562
 563    func deleteTrackedDomain(_ trackedDomain: TrackedDomain) {
 564        trackedDomains.removeAll { $0.id == trackedDomain.id }
 565        history.indices.forEach { index in
 566            if history[index].trackedDomainID == trackedDomain.id {
 567                history[index].trackedDomainID = nil
 568            }
 569        }
 570        persistTrackedDomains()
 571        persistHistory()
 572    }
 573
 574    func togglePinned(for trackedDomain: TrackedDomain) {
 575        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 576        trackedDomains[index].isPinned.toggle()
 577        persistTrackedDomains()
 578    }
 579
 580    func updateNote(_ note: String, for trackedDomain: TrackedDomain) {
 581        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 582        trackedDomains[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
 583        persistTrackedDomains()
 584    }
 585
 586    func removeHistoryEntries(at offsets: IndexSet) {
 587        history.remove(atOffsets: offsets)
 588        persistHistory()
 589    }
 590
 591    func removeHistoryEntries(withIDs ids: [UUID]) {
 592        history.removeAll { ids.contains($0.id) }
 593        persistHistory()
 594    }
 595
 596    func clearHistory() {
 597        history.removeAll()
 598        persistHistory()
 599    }
 600
 601    func clearLookupCache() {
 602        Task {
 603            await LookupRuntime.shared.clearCache()
 604        }
 605    }
 606
 607    func clearRecentSearches() {
 608        recentSearches.removeAll()
 609        UserDefaults.standard.removeObject(forKey: Self.recentSearchesKey)
 610    }
 611
 612    func rerunLookup(from entry: HistoryEntry) {
 613        UserDefaults.standard.set(entry.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
 614        domain = entry.domain
 615        run()
 616        rerunNavigationToken = UUID()
 617    }
 618
 619    func reset() {
 620        lookupTask?.cancel()
 621        customPortScanTask?.cancel()
 622        batchTask?.cancel()
 623        hasRun = false
 624        searchedDomain = ""
 625        lastLookupDurationMs = nil
 626        currentDiffSections = []
 627        currentChangeSummary = nil
 628        ownershipDiff = []
 629        refreshingTrackedDomainID = nil
 630        clearBatchState()
 631        clearLookupState()
 632    }
 633
 634    func run() {
 635        let target = trimmedDomain
 636        guard !target.isEmpty else { return }
 637        clearBatchState()
 638        let lookupID = beginLookup(for: target)
 639
 640        lookupTask = Task { [weak self] in
 641            guard let self else { return }
 642            _ = await self.performLookup(domain: target, lookupID: lookupID)
 643        }
 644    }
 645
 646    func runBulkLookup() {
 647        let domains = parsedDomains(from: bulkInput)
 648        guard !domains.isEmpty else { return }
 649        startBatchLookup(domains: domains, source: .manual)
 650    }
 651
 652    func refreshAllTrackedDomains() {
 653        startBatchLookup(domains: sortedTrackedDomains.map(\.domain), source: .watchlistRefresh)
 654    }
 655
 656    func cancelBatchLookup() {
 657        batchTask?.cancel()
 658        batchLookupRunning = false
 659        batchCurrentDomain = nil
 660        activeBatchDomains = []
 661        refreshingTrackedDomainID = nil
 662
 663        for index in batchResults.indices where batchResults[index].status == .pending || batchResults[index].status == .running {
 664            batchResults[index] = BatchLookupResult(
 665                id: batchResults[index].id,
 666                domain: batchResults[index].domain,
 667                historyEntryID: batchResults[index].historyEntryID,
 668                availability: batchResults[index].availability,
 669                primaryIP: batchResults[index].primaryIP,
 670                quickStatus: "Cancelled",
 671                summaryMessage: batchResults[index].summaryMessage,
 672                changeSeverity: batchResults[index].changeSeverity,
 673                certificateWarningLevel: batchResults[index].certificateWarningLevel,
 674                timestamp: Date(),
 675                status: .failed,
 676                errorMessage: "Lookup cancelled"
 677            )
 678        }
 679    }
 680
 681    func runCustomPortScan(ports: [UInt16]) async {
 682        guard !searchedDomain.isEmpty else {
 683            customPortScanError = "Run a domain lookup first"
 684            return
 685        }
 686
 687        guard !ports.isEmpty else {
 688            customPortScanError = "Enter at least one valid port"
 689            customPortResults = []
 690            return
 691        }
 692
 693        customPortScanTask?.cancel()
 694        let domain = searchedDomain
 695        let lookupID = activeLookupID
 696
 697        customPortScanLoading = true
 698        customPortScanError = nil
 699        customPortResults = []
 700
 701        customPortScanTask = Task { [weak self] in
 702            guard let self else { return }
 703            let result = await PortScanService.scanPorts(domain: domain, ports: ports, timeout: 3.0)
 704            guard !Task.isCancelled, self.isCurrentLookup(lookupID) else { return }
 705            self.applyCustomPortResult(result)
 706        }
 707    }
 708
 709    func exportText() -> String {
 710        guard let currentReport else { return "No results available." }
 711        return DomainReportExporter.text(for: currentReport)
 712    }
 713
 714    func exportCSV() -> String {
 715        guard let currentReport else { return DomainReportExporter.csv(for: []) }
 716        return DomainReportExporter.csv(for: [currentReport])
 717    }
 718
 719    func exportJSONData() -> Data? {
 720        guard let currentReport else { return nil }
 721        return try? DomainReportExporter.data(for: currentReport, format: .json)
 722    }
 723
 724    func exportBatchText() -> String {
 725        DomainReportExporter.batchText(
 726            for: currentBatchReports(),
 727            title: batchLookupSource == .watchlistRefresh ? "Tracked Domains Export" : "Batch Results Export"
 728        )
 729    }
 730
 731    func exportBatchCSV() -> String {
 732        DomainReportExporter.csv(for: currentBatchReports())
 733    }
 734
 735    func exportBatchJSONData() -> Data? {
 736        try? DomainReportExporter.data(
 737            for: currentBatchReports(),
 738            format: .json,
 739            title: batchLookupSource == .watchlistRefresh ? "Tracked Domains Export" : "Batch Results Export"
 740        )
 741    }
 742
 743    func exportTrackedDomainsCSV(domains: [TrackedDomain]) -> String {
 744        DomainReportExporter.csv(for: reports(for: domains))
 745    }
 746
 747    func exportTrackedDomainsText(domains: [TrackedDomain]) -> String {
 748        DomainReportExporter.batchText(
 749            for: reports(for: domains),
 750            title: "Tracked Domains Export"
 751        )
 752    }
 753
 754    func exportTrackedDomainsJSONData(domains: [TrackedDomain]) -> Data? {
 755        try? DomainReportExporter.data(
 756            for: reports(for: domains),
 757            format: .json,
 758            title: "Tracked Domains Export"
 759        )
 760    }
 761
 762    private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? {
 763        let previous = previousSnapshot(
 764            for: domain,
 765            trackedDomainID: currentTrackedDomain?.id,
 766            replacingLatest: false
 767        )
 768        let inspectedSnapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previous)
 769        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
 770
 771        let snapshot = Self.resolvedSnapshotAfterFallback(inspectedSnapshot, previousSnapshot: previous)
 772        applySnapshot(snapshot)
 773        lastLookupDurationMs = snapshot.totalLookupDurationMs
 774        refreshingTrackedDomainID = nil
 775
 776        guard snapshot.statusMessage == nil else {
 777            return history.first(where: { $0.id == snapshot.historyEntryID })
 778        }
 779
 780        return saveHistoryEntry(replaceLatest: false)
 781    }
 782
 783    private func applySnapshot(_ snapshot: LookupSnapshot) {
 784        currentHistoryEntryID = snapshot.historyEntryID
 785        currentSnapshotTimestamp = snapshot.timestamp
 786        currentResultSource = snapshot.resultSource
 787        currentCachedSections = snapshot.cachedSections
 788        currentStatusMessage = snapshot.statusMessage
 789        currentChangeSummary = snapshot.changeSummary
 790        currentDiffSections = []
 791        ownershipDiff = []
 792
 793        dnsSections = snapshot.dnsSections
 794        dnsError = snapshot.dnsError
 795        availabilityResult = snapshot.availabilityResult
 796        suggestions = snapshot.suggestions
 797        sslInfo = snapshot.sslInfo
 798        sslError = snapshot.sslError
 799        hstsPreloaded = snapshot.hstsPreloaded
 800        httpHeaders = snapshot.httpHeaders
 801        httpSecurityGrade = snapshot.httpSecurityGrade
 802        httpStatusCode = snapshot.httpStatusCode
 803        httpResponseTimeMs = snapshot.httpResponseTimeMs
 804        httpProtocol = snapshot.httpProtocol
 805        http3Advertised = snapshot.http3Advertised
 806        httpHeadersError = snapshot.httpHeadersError
 807        reachabilityResults = snapshot.reachabilityResults
 808        reachabilityError = snapshot.reachabilityError
 809        ipGeolocation = snapshot.ipGeolocation
 810        ipGeolocationError = snapshot.ipGeolocationError
 811        emailSecurity = snapshot.emailSecurity
 812        emailSecurityError = snapshot.emailSecurityError
 813        ownershipResult = snapshot.ownership
 814        ownershipError = snapshot.ownershipError
 815        ptrRecord = snapshot.ptrRecord
 816        ptrError = snapshot.ptrError
 817        redirectChain = snapshot.redirectChain
 818        redirectChainError = snapshot.redirectChainError
 819        subdomains = snapshot.subdomains
 820        subdomainsError = snapshot.subdomainsError
 821        portScanResults = snapshot.portScanResults.filter { $0.kind == .standard }
 822        customPortResults = snapshot.portScanResults.filter { $0.kind == .custom }
 823        portScanError = snapshot.portScanError
 824        customPortScanError = nil
 825
 826        dnsLoading = false
 827        availabilityLoading = false
 828        suggestionsLoading = false
 829        sslLoading = false
 830        hstsLoading = false
 831        httpHeadersLoading = false
 832        reachabilityLoading = false
 833        ipGeolocationLoading = false
 834        emailSecurityLoading = false
 835        ownershipLoading = false
 836        ptrLoading = false
 837        redirectChainLoading = false
 838        subdomainsLoading = false
 839        portScanLoading = false
 840        customPortScanLoading = false
 841    }
 842
 843    private static func resolvedSnapshotAfterFallback(
 844        _ snapshot: LookupSnapshot,
 845        previousSnapshot: LookupSnapshot?
 846    ) -> LookupSnapshot {
 847        guard shouldFallbackToSnapshot(snapshot), let previousSnapshot else {
 848            return snapshot
 849        }
 850
 851        return LookupSnapshot(
 852            historyEntryID: previousSnapshot.historyEntryID,
 853            domain: previousSnapshot.domain,
 854            timestamp: previousSnapshot.timestamp,
 855            trackedDomainID: previousSnapshot.trackedDomainID,
 856            resolverDisplayName: previousSnapshot.resolverDisplayName,
 857            resolverURLString: previousSnapshot.resolverURLString,
 858            totalLookupDurationMs: previousSnapshot.totalLookupDurationMs,
 859            dnsSections: previousSnapshot.dnsSections,
 860            dnsError: previousSnapshot.dnsError,
 861            availabilityResult: previousSnapshot.availabilityResult,
 862            suggestions: previousSnapshot.suggestions,
 863            sslInfo: previousSnapshot.sslInfo,
 864            sslError: previousSnapshot.sslError,
 865            hstsPreloaded: previousSnapshot.hstsPreloaded,
 866            httpHeaders: previousSnapshot.httpHeaders,
 867            httpSecurityGrade: previousSnapshot.httpSecurityGrade,
 868            httpStatusCode: previousSnapshot.httpStatusCode,
 869            httpResponseTimeMs: previousSnapshot.httpResponseTimeMs,
 870            httpProtocol: previousSnapshot.httpProtocol,
 871            http3Advertised: previousSnapshot.http3Advertised,
 872            httpHeadersError: previousSnapshot.httpHeadersError,
 873            reachabilityResults: previousSnapshot.reachabilityResults,
 874            reachabilityError: previousSnapshot.reachabilityError,
 875            ipGeolocation: previousSnapshot.ipGeolocation,
 876            ipGeolocationError: previousSnapshot.ipGeolocationError,
 877            emailSecurity: previousSnapshot.emailSecurity,
 878            emailSecurityError: previousSnapshot.emailSecurityError,
 879            ownership: previousSnapshot.ownership,
 880            ownershipError: previousSnapshot.ownershipError,
 881            ptrRecord: previousSnapshot.ptrRecord,
 882            ptrError: previousSnapshot.ptrError,
 883            redirectChain: previousSnapshot.redirectChain,
 884            redirectChainError: previousSnapshot.redirectChainError,
 885            subdomains: previousSnapshot.subdomains,
 886            subdomainsError: previousSnapshot.subdomainsError,
 887            portScanResults: previousSnapshot.portScanResults,
 888            portScanError: previousSnapshot.portScanError,
 889            changeSummary: previousSnapshot.changeSummary,
 890            resultSource: .snapshot,
 891            cachedSections: [],
 892            statusMessage: "Last known result • \(previousSnapshot.timestamp.formatted(date: .abbreviated, time: .shortened))"
 893        )
 894    }
 895
 896    private static func shouldFallbackToSnapshot(_ snapshot: LookupSnapshot) -> Bool {
 897        let candidateMessages = [
 898            snapshot.dnsError,
 899            snapshot.httpHeadersError,
 900            snapshot.sslError,
 901            snapshot.ownershipError,
 902            snapshot.subdomainsError,
 903            snapshot.redirectChainError,
 904            snapshot.ipGeolocationError
 905        ]
 906        .compactMap { $0?.lowercased() }
 907
 908        guard !candidateMessages.isEmpty else { return false }
 909        let failedDueToConnectivity = candidateMessages.allSatisfy { message in
 910            message.hasPrefix("network error:") || message.hasPrefix("timeout:") || message.hasPrefix("rate limit:")
 911        }
 912
 913        let hasMaterialData = !snapshot.dnsSections.isEmpty
 914            || !snapshot.httpHeaders.isEmpty
 915            || snapshot.sslInfo != nil
 916            || snapshot.ownership != nil
 917            || !snapshot.subdomains.isEmpty
 918
 919        return failedDueToConnectivity && !hasMaterialData
 920    }
 921
 922    private func runDNS(domain: String, lookupID: UUID) async {
 923        let result = await DNSLookupService.lookupAll(domain: domain)
 924        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 925        switch result {
 926        case let .success(sections):
 927            dnsSections = sections
 928            dnsError = nil
 929        case let .empty(message):
 930            dnsSections = []
 931            dnsError = message
 932        case let .error(message):
 933            dnsSections = []
 934            dnsError = message
 935        }
 936        dnsLoading = false
 937    }
 938
 939    private func runAvailability(domain: String, lookupID: UUID) async {
 940        let result = await DomainAvailabilityService.check(domain: domain)
 941        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 942        availabilityResult = result
 943        availabilityLoading = false
 944        updateTrackedDomainAvailability(for: result.domain, status: result.status)
 945    }
 946
 947    private func runSSL(domain: String, lookupID: UUID) async {
 948        let result = await SSLCheckService.check(domain: domain)
 949        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 950        switch result {
 951        case let .success(info):
 952            sslInfo = info
 953            sslError = nil
 954        case let .empty(message):
 955            sslInfo = nil
 956            sslError = message
 957        case let .error(message):
 958            sslInfo = nil
 959            sslError = message
 960        }
 961        sslLoading = false
 962    }
 963
 964    private func runHSTSPreload(domain: String, lookupID: UUID) async {
 965        let result = await SSLCheckService.checkHSTSPreload(domain: domain)
 966        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 967        hstsPreloaded = result
 968        hstsLoading = false
 969    }
 970
 971    private func runHTTPHeaders(domain: String, lookupID: UUID) async {
 972        let result = await HTTPHeadersService.fetch(domain: domain)
 973        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 974        switch result {
 975        case let .success(headersResult):
 976            httpHeaders = headersResult.headers
 977            httpSecurityGrade = HTTPSecurityGrade.grade(for: headersResult.headers).rawValue
 978            httpStatusCode = headersResult.statusCode
 979            httpResponseTimeMs = headersResult.responseTimeMs
 980            httpProtocol = headersResult.httpProtocol
 981            http3Advertised = headersResult.http3Advertised
 982            httpHeadersError = nil
 983        case let .empty(message):
 984            httpHeaders = []
 985            httpSecurityGrade = nil
 986            httpStatusCode = nil
 987            httpResponseTimeMs = nil
 988            httpProtocol = nil
 989            http3Advertised = false
 990            httpHeadersError = message
 991        case let .error(message):
 992            httpHeaders = []
 993            httpSecurityGrade = nil
 994            httpStatusCode = nil
 995            httpResponseTimeMs = nil
 996            httpProtocol = nil
 997            http3Advertised = false
 998            httpHeadersError = message
 999        }
1000        httpHeadersLoading = false
1001    }
1002
1003    private func runReachability(domain: String, lookupID: UUID) async {
1004        let result = await ReachabilityService.checkAll(domain: domain)
1005        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1006        switch result {
1007        case let .success(results):
1008            reachabilityResults = results
1009            reachabilityError = nil
1010        case let .empty(message):
1011            reachabilityResults = []
1012            reachabilityError = message
1013        case let .error(message):
1014            reachabilityResults = []
1015            reachabilityError = message
1016        }
1017        reachabilityLoading = false
1018    }
1019
1020    private func runEmailSecurity(domain: String, txtRecords: [DNSRecord], lookupID: UUID) async {
1021        let result = await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords)
1022        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1023        switch result {
1024        case let .success(emailResult):
1025            emailSecurity = emailResult
1026            emailSecurityError = nil
1027        case let .empty(message):
1028            emailSecurity = nil
1029            emailSecurityError = message
1030        case let .error(message):
1031            emailSecurity = nil
1032            emailSecurityError = message
1033        }
1034        emailSecurityLoading = false
1035    }
1036
1037    private func runOwnership(domain: String, lookupID: UUID) async {
1038        let result = await DomainOwnershipService.lookup(domain: domain)
1039        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1040        switch result {
1041        case let .success(ownership):
1042            ownershipResult = ownership
1043            ownershipError = nil
1044        case let .empty(message):
1045            ownershipResult = nil
1046            ownershipError = message
1047        case let .error(message):
1048            ownershipResult = nil
1049            ownershipError = message
1050        }
1051        ownershipLoading = false
1052    }
1053
1054    private func runReverseDNS(ip: String, lookupID: UUID) async {
1055        let result = await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString)
1056        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1057        switch result {
1058        case let .success(record):
1059            ptrRecord = record
1060            ptrError = nil
1061        case let .empty(message):
1062            ptrRecord = nil
1063            ptrError = message
1064        case let .error(message):
1065            ptrRecord = nil
1066            ptrError = message
1067        }
1068        ptrLoading = false
1069    }
1070
1071    private func runRedirectChain(domain: String, lookupID: UUID) async {
1072        let result = await RedirectChainService.trace(domain: domain)
1073        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1074        switch result {
1075        case let .success(hops):
1076            redirectChain = hops
1077            redirectChainError = nil
1078        case let .empty(message):
1079            redirectChain = []
1080            redirectChainError = message
1081        case let .error(message):
1082            redirectChain = []
1083            redirectChainError = message
1084        }
1085        redirectChainLoading = false
1086    }
1087
1088    private func runSubdomains(domain: String, lookupID: UUID) async {
1089        let result = await SubdomainDiscoveryService.discover(for: domain)
1090        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1091        switch result {
1092        case let .success(results):
1093            subdomains = results
1094            subdomainsError = nil
1095        case let .empty(message):
1096            subdomains = []
1097            subdomainsError = message
1098        case let .error(message):
1099            subdomains = []
1100            subdomainsError = message
1101        }
1102        subdomainsLoading = false
1103    }
1104
1105    private func runPortScan(domain: String, lookupID: UUID) async {
1106        let result = await PortScanService.scanAll(domain: domain)
1107        switch result {
1108        case let .success(results):
1109            let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain)
1110            guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1111            portScanResults = enrichedResults
1112            portScanError = nil
1113        case let .empty(message):
1114            guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1115            portScanResults = []
1116            portScanError = message
1117        case let .error(message):
1118            guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1119            portScanResults = []
1120            portScanError = message
1121        }
1122        portScanLoading = false
1123    }
1124
1125    private func runIPGeolocation(ip: String, lookupID: UUID) async {
1126        let result = await IPGeolocationService.lookup(ip: ip)
1127        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1128        switch result {
1129        case let .success(geolocation):
1130            ipGeolocation = geolocation
1131            ipGeolocationError = nil
1132        case let .empty(message):
1133            ipGeolocation = nil
1134            ipGeolocationError = message
1135        case let .error(message):
1136            ipGeolocation = nil
1137            ipGeolocationError = message
1138        }
1139        ipGeolocationLoading = false
1140    }
1141
1142    private func finishDependentWithoutPrimaryIP(lookupID: UUID) async {
1143        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1144        ptrLoading = false
1145        ptrError = "No A record available"
1146        ipGeolocationLoading = false
1147        ipGeolocationError = "No A record available"
1148    }
1149
1150    private func runSuggestions(domain: String, lookupID: UUID) async {
1151        let results = await DomainAvailabilityService.suggestions(for: domain)
1152        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1153        suggestions = results
1154        suggestionsLoading = false
1155    }
1156
1157    private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) {
1158        switch result {
1159        case let .success(results):
1160            customPortResults = results
1161            customPortScanError = nil
1162            _ = saveHistoryEntry(replaceLatest: true)
1163        case let .empty(message):
1164            customPortResults = []
1165            customPortScanError = message
1166        case let .error(message):
1167            customPortResults = []
1168            customPortScanError = message
1169        }
1170        customPortScanLoading = false
1171    }
1172
1173    private static func performBatchLookup(domain: String, previousSnapshot: LookupSnapshot?) async -> BatchLookupPayload? {
1174        guard !Task.isCancelled else { return nil }
1175        let inspectionService = DomainInspectionService()
1176        let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
1177        guard !Task.isCancelled else { return nil }
1178        return BatchLookupPayload(snapshot: resolvedSnapshotAfterFallback(snapshot, previousSnapshot: previousSnapshot))
1179    }
1180
1181    private static func enrichOpenPortBanners(_ results: [PortScanResult], domain: String) async -> [PortScanResult] {
1182        let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
1183            for result in results where result.open {
1184                group.addTask {
1185                    let banner = await PortScanService.grabBanner(host: domain, port: result.port)
1186                    return (result.port, banner)
1187                }
1188            }
1189
1190            var collected: [UInt16: String] = [:]
1191            for await (port, banner) in group {
1192                if let banner {
1193                    collected[port] = banner
1194                }
1195            }
1196            return collected
1197        }
1198
1199        return results.map { result in
1200            var updated = result
1201            updated.banner = banners[result.port]
1202            return updated
1203        }
1204    }
1205
1206    private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
1207        await Self.enrichOpenPortBanners(results, domain: domain)
1208    }
1209
1210    @discardableResult
1211    private func saveHistoryEntry(replaceLatest: Bool) -> HistoryEntry? {
1212        guard !searchedDomain.isEmpty else { return nil }
1213        return saveHistoryEntry(from: currentSnapshot, replaceLatest: replaceLatest, updateCurrentState: true)
1214    }
1215
1216    @discardableResult
1217    private func saveHistoryEntry(from snapshot: LookupSnapshot, replaceLatest: Bool, updateCurrentState: Bool) -> HistoryEntry? {
1218        let trackedDomainID = snapshot.trackedDomainID ?? trackedDomain(for: snapshot.domain)?.id
1219        let previousSnapshot = previousSnapshot(for: snapshot.domain, trackedDomainID: trackedDomainID, replacingLatest: replaceLatest)
1220        let changeSummary = previousSnapshot.map {
1221            DomainDiffService.summary(from: $0, to: snapshot, generatedAt: snapshot.timestamp)
1222        }
1223        let diffSections = previousSnapshot.map { DomainDiffService.diff(from: $0, to: snapshot) } ?? []
1224
1225        if updateCurrentState {
1226            currentChangeSummary = changeSummary
1227            currentDiffSections = diffSections
1228            ownershipDiff = diffSections.first(where: { $0.title == "Ownership" })?.items.filter(\.hasChanges) ?? []
1229        }
1230
1231        let entry = HistoryEntry(
1232            domain: snapshot.domain,
1233            timestamp: snapshot.timestamp,
1234            trackedDomainID: trackedDomainID,
1235            dnsSections: snapshot.dnsSections,
1236            sslInfo: snapshot.sslInfo,
1237            httpHeaders: snapshot.httpHeaders,
1238            reachabilityResults: snapshot.reachabilityResults,
1239            ipGeolocation: snapshot.ipGeolocation,
1240            emailSecurity: snapshot.emailSecurity,
1241            mtaSts: snapshot.emailSecurity?.mtaSts,
1242            ownership: snapshot.ownership,
1243            ptrRecord: snapshot.ptrRecord,
1244            redirectChain: snapshot.redirectChain,
1245            subdomains: snapshot.subdomains,
1246            portScanResults: snapshot.portScanResults,
1247            hstsPreloaded: snapshot.hstsPreloaded,
1248            availabilityResult: snapshot.availabilityResult,
1249            suggestions: snapshot.suggestions,
1250            resolverDisplayName: snapshot.resolverDisplayName,
1251            resolverURLString: snapshot.resolverURLString,
1252            totalLookupDurationMs: snapshot.totalLookupDurationMs,
1253            primaryIP: Self.primaryIPAddress(from: snapshot),
1254            finalRedirectURL: Self.finalRedirectTarget(from: snapshot),
1255            tlsStatusSummary: Self.httpsSummary(from: snapshot),
1256            emailSecuritySummary: Self.emailSummary(from: snapshot),
1257            httpGradeSummary: snapshot.httpSecurityGrade ?? snapshot.httpHeadersError,
1258            changeSummary: changeSummary,
1259            sslError: snapshot.sslError,
1260            httpHeadersError: snapshot.httpHeadersError,
1261            reachabilityError: snapshot.reachabilityError,
1262            ipGeolocationError: snapshot.ipGeolocationError,
1263            emailSecurityError: snapshot.emailSecurityError,
1264            ownershipError: snapshot.ownershipError,
1265            ptrError: snapshot.ptrError,
1266            redirectChainError: snapshot.redirectChainError,
1267            subdomainsError: snapshot.subdomainsError,
1268            portScanError: snapshot.portScanError
1269        )
1270
1271        if updateCurrentState {
1272            currentHistoryEntryID = entry.id
1273        }
1274
1275        if replaceLatest, !history.isEmpty, history[0].domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame {
1276            history[0] = entry
1277        } else {
1278            history.insert(entry, at: 0)
1279            if history.count > Self.maxHistory {
1280                history = Array(history.prefix(Self.maxHistory))
1281            }
1282        }
1283
1284        updateTrackedDomainSnapshotMetadata(
1285            domain: snapshot.domain,
1286            snapshotID: entry.id,
1287            availabilityStatus: snapshot.availabilityResult?.status,
1288            updatedAt: snapshot.timestamp,
1289            changeSummary: changeSummary,
1290            changeSeverity: changeSummary?.severity,
1291            certificateWarningLevel: DomainDiffService.certificateWarningLevel(for: snapshot),
1292            certificateDaysRemaining: snapshot.sslInfo?.daysUntilExpiry
1293        )
1294        persistHistory()
1295        notifyIfNeeded(for: entry, snapshot: snapshot, previousSnapshot: previousSnapshot)
1296        return entry
1297    }
1298
1299    private func persistHistory() {
1300        if let data = try? JSONEncoder().encode(history) {
1301            UserDefaults.standard.set(data, forKey: Self.historyKey)
1302        }
1303    }
1304
1305    private func persistTrackedDomains() {
1306        if let data = try? JSONEncoder().encode(trackedDomains) {
1307            UserDefaults.standard.set(data, forKey: Self.trackedDomainsKey)
1308        }
1309    }
1310
1311    private func updateTrackedDomainAvailability(for domain: String, status: DomainAvailabilityStatus) {
1312        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1313            return
1314        }
1315        trackedDomains[index].lastKnownAvailability = status
1316        persistTrackedDomains()
1317    }
1318
1319    private func updateTrackedDomainSnapshotMetadata(
1320        domain: String,
1321        snapshotID: UUID,
1322        availabilityStatus: DomainAvailabilityStatus?,
1323        updatedAt: Date,
1324        changeSummary: DomainChangeSummary?,
1325        changeSeverity: ChangeSeverity?,
1326        certificateWarningLevel: CertificateWarningLevel,
1327        certificateDaysRemaining: Int?
1328    ) {
1329        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1330            return
1331        }
1332        trackedDomains[index].lastSnapshotID = snapshotID
1333        trackedDomains[index].lastKnownAvailability = availabilityStatus
1334        trackedDomains[index].updatedAt = updatedAt
1335        trackedDomains[index].lastChangeSummary = changeSummary
1336        trackedDomains[index].lastChangeSeverity = changeSeverity
1337        trackedDomains[index].certificateWarningLevel = certificateWarningLevel
1338        trackedDomains[index].certificateDaysRemaining = certificateDaysRemaining
1339        persistTrackedDomains()
1340    }
1341
1342    private func notifyIfNeeded(for entry: HistoryEntry, snapshot: LookupSnapshot, previousSnapshot: LookupSnapshot?) {
1343        guard notificationsAuthorized, entry.trackedDomainID != nil else { return }
1344
1345        Task {
1346            if let summary = entry.changeSummary, summary.hasChanges {
1347                await LocalNotificationService.shared.notifyDomainEvent(
1348                    domain: entry.domain,
1349                    message: summary.message,
1350                    severity: summary.severity
1351                )
1352            }
1353
1354            let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: snapshot)
1355            if certificateWarningLevel == .critical, let daysRemaining = snapshot.sslInfo?.daysUntilExpiry {
1356                await LocalNotificationService.shared.notifyCertificateWarning(
1357                    domain: entry.domain,
1358                    daysRemaining: daysRemaining
1359                )
1360            }
1361
1362            if let previousStatus = previousSnapshot?.availabilityResult?.status,
1363               let newStatus = snapshot.availabilityResult?.status,
1364               previousStatus != newStatus {
1365                await LocalNotificationService.shared.notifyDomainEvent(
1366                    domain: entry.domain,
1367                    message: "Availability changed",
1368                    severity: .high
1369                )
1370            }
1371        }
1372    }
1373
1374    private func previousSnapshot(for domain: String, trackedDomainID: UUID?, replacingLatest: Bool) -> LookupSnapshot? {
1375        let matchingEntries = history.filter { entry in
1376            if let trackedDomainID {
1377                return entry.trackedDomainID == trackedDomainID
1378            }
1379            return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1380        }
1381
1382        if replacingLatest {
1383            return matchingEntries.dropFirst().first?.snapshot
1384        }
1385        return matchingEntries.first?.snapshot
1386    }
1387
1388    private func trackedDomain(for domain: String) -> TrackedDomain? {
1389        trackedDomains.first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }
1390    }
1391
1392    private func normalizedDomain(_ domain: String) -> String {
1393        domain
1394            .trimmingCharacters(in: .whitespacesAndNewlines)
1395            .replacingOccurrences(of: "https://", with: "")
1396            .replacingOccurrences(of: "http://", with: "")
1397            .components(separatedBy: "/")
1398            .first?
1399            .lowercased() ?? ""
1400    }
1401
1402    private func linkTrackedDomainHistory(for domain: String) {
1403        guard let trackedDomain = trackedDomain(for: domain) else { return }
1404        var didChange = false
1405
1406        for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
1407            if history[index].trackedDomainID != trackedDomain.id {
1408                history[index].trackedDomainID = trackedDomain.id
1409                didChange = true
1410            }
1411        }
1412
1413        if didChange {
1414            persistHistory()
1415        }
1416
1417        if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
1418           let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
1419            trackedDomains[trackedIndex].lastSnapshotID = latestEntry.id
1420            trackedDomains[trackedIndex].lastChangeSummary = latestEntry.changeSummary
1421            trackedDomains[trackedIndex].lastChangeSeverity = latestEntry.changeSummary?.severity
1422            trackedDomains[trackedIndex].lastKnownAvailability = latestEntry.availabilityResult?.status
1423            trackedDomains[trackedIndex].certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: latestEntry.snapshot)
1424            trackedDomains[trackedIndex].certificateDaysRemaining = latestEntry.sslInfo?.daysUntilExpiry
1425            trackedDomains[trackedIndex].updatedAt = latestEntry.timestamp
1426            persistTrackedDomains()
1427        }
1428    }
1429
1430    private func addRecentSearch(_ domain: String) {
1431        recentSearches.removeAll { $0.lowercased() == domain.lowercased() }
1432        recentSearches.insert(domain, at: 0)
1433        if recentSearches.count > Self.maxRecent {
1434            recentSearches = Array(recentSearches.prefix(Self.maxRecent))
1435        }
1436        UserDefaults.standard.set(recentSearches, forKey: Self.recentSearchesKey)
1437    }
1438
1439    private func beginLookup(for target: String, cancelExistingTask: Bool = true) -> UUID {
1440        if cancelExistingTask {
1441            lookupTask?.cancel()
1442        }
1443        customPortScanTask?.cancel()
1444
1445        let lookupID = UUID()
1446        activeLookupID = lookupID
1447        lookupStartedAt = Date()
1448        lastLookupDurationMs = nil
1449        addRecentSearch(target)
1450        searchedDomain = target
1451        hasRun = true
1452        currentHistoryEntryID = nil
1453        currentSnapshotTimestamp = Date()
1454        currentResultSource = .live
1455        currentCachedSections = []
1456        currentStatusMessage = nil
1457        currentDiffSections = []
1458        currentChangeSummary = nil
1459        ownershipDiff = []
1460        clearLookupState()
1461        setAllLoadingStates(true)
1462        customPortScanLoading = false
1463        return lookupID
1464    }
1465
1466    private func startBatchLookup(domains: [String], source: BatchLookupSource) {
1467        guard !domains.isEmpty else { return }
1468        guard !batchLookupRunning else { return }
1469
1470        let now = Date()
1471        if let lastBatchStartedAt, now.timeIntervalSince(lastBatchStartedAt) < 1 {
1472            return
1473        }
1474
1475        lastBatchStartedAt = now
1476        clearBatchState()
1477        batchLookupSource = source
1478        batchTotalCount = domains.count
1479        batchLookupRunning = true
1480        batchResults = domains.map {
1481            BatchLookupResult(
1482                domain: $0,
1483                historyEntryID: nil,
1484                availability: nil,
1485                primaryIP: nil,
1486                quickStatus: "Pending",
1487                timestamp: Date(),
1488                status: .pending
1489            )
1490        }
1491
1492        lookupTask?.cancel()
1493        customPortScanTask?.cancel()
1494        batchTask?.cancel()
1495
1496        batchTask = Task { [weak self] in
1497            guard let self else { return }
1498            self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
1499            await self.runBatchLookup(domains: domains, source: source)
1500        }
1501    }
1502
1503    private func clearBatchState() {
1504        batchResults = []
1505        batchLookupSource = .manual
1506        batchCurrentDomain = nil
1507        batchCompletedCount = 0
1508        batchTotalCount = 0
1509        batchLookupRunning = false
1510        latestBatchSweepSummary = nil
1511        activeBatchDomains = []
1512        batchTask = nil
1513    }
1514
1515    private func parsedDomains(from input: String) -> [String] {
1516        let separators = CharacterSet(charactersIn: ",\n")
1517        var seen = Set<String>()
1518
1519        return input
1520            .components(separatedBy: separators)
1521            .map(normalizedDomain)
1522            .filter { !$0.isEmpty }
1523            .filter { seen.insert($0).inserted }
1524    }
1525
1526    private func runBatchLookup(domains: [String], source: BatchLookupSource) async {
1527        let concurrencyLimit = min(source == .watchlistRefresh ? 4 : 3, max(domains.count, 1))
1528        var nextIndex = 0
1529
1530        await withTaskGroup(of: (String, BatchLookupPayload?).self) { group in
1531            for _ in 0..<concurrencyLimit {
1532                guard nextIndex < domains.count else { break }
1533                let domain = domains[nextIndex]
1534                nextIndex += 1
1535                enqueueBatchLookup(domain: domain, source: source, group: &group)
1536            }
1537
1538            while let (domain, payload) = await group.next() {
1539                completeBatchLookup(domain: domain, payload: payload)
1540
1541                if nextIndex < domains.count, !Task.isCancelled {
1542                    let nextDomain = domains[nextIndex]
1543                    nextIndex += 1
1544                    enqueueBatchLookup(domain: nextDomain, source: source, group: &group)
1545                }
1546            }
1547        }
1548
1549        finishBatchLookup(source: source)
1550    }
1551
1552    private func enqueueBatchLookup(
1553        domain: String,
1554        source: BatchLookupSource,
1555        group: inout TaskGroup<(String, BatchLookupPayload?)>
1556    ) {
1557        activeBatchDomains.append(domain)
1558        batchCurrentDomain = activeBatchDomains.first
1559        if source == .watchlistRefresh {
1560            refreshingTrackedDomainID = trackedDomain(for: domain)?.id
1561        }
1562        updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil)
1563        let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false)
1564
1565        group.addTask { [domain, previousSnapshot] in
1566            let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot)
1567            return (domain, payload)
1568        }
1569    }
1570
1571    private func completeBatchLookup(domain: String, payload: BatchLookupPayload?) {
1572        activeBatchDomains.removeAll { $0.caseInsensitiveCompare(domain) == .orderedSame }
1573        batchCurrentDomain = activeBatchDomains.first
1574
1575        guard let payload else {
1576            updateBatchResult(
1577                domain: domain,
1578                status: .failed,
1579                quickStatus: "Failed",
1580                entry: nil,
1581                resultSource: .live,
1582                errorMessage: "Lookup cancelled"
1583            )
1584            batchCompletedCount += 1
1585            return
1586        }
1587
1588        let entry: HistoryEntry?
1589        if payload.snapshot.statusMessage == nil {
1590            entry = saveHistoryEntry(from: payload.snapshot, replaceLatest: false, updateCurrentState: false)
1591        } else {
1592            entry = payload.snapshot.historyEntryID.flatMap { id in
1593                history.first(where: { $0.id == id })
1594            }
1595        }
1596        let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: payload.snapshot)
1597        let quickStatus: String
1598        if entry?.changeSummary?.hasChanges == true {
1599            quickStatus = entry?.changeSummary?.severity == .high ? "High" : "Changed"
1600        } else if certificateWarningLevel != .none {
1601            quickStatus = certificateWarningLevel == .critical ? "Critical" : "Warning"
1602        } else {
1603            quickStatus = "Unchanged"
1604        }
1605
1606        updateBatchResult(
1607            domain: domain,
1608            status: .completed,
1609            quickStatus: quickStatus,
1610            entry: entry,
1611            resultSource: payload.snapshot.resultSource,
1612            errorMessage: payload.snapshot.statusMessage
1613        )
1614        batchCompletedCount += 1
1615    }
1616
1617    private func finishBatchLookup(source: BatchLookupSource) {
1618        batchLookupRunning = false
1619        batchCurrentDomain = nil
1620        activeBatchDomains = []
1621        refreshingTrackedDomainID = nil
1622        batchTask = nil
1623
1624        let summary = BatchSweepSummary(
1625            source: source,
1626            totalDomains: batchResults.count,
1627            changedDomains: batchResults.filter { $0.quickStatus == "Changed" || $0.quickStatus == "High" }.count,
1628            unchangedDomains: batchResults.filter { $0.quickStatus == "Unchanged" && $0.status == .completed }.count,
1629            warningDomains: batchResults.filter { $0.certificateWarningLevel != .none }.count,
1630            results: batchResults.sorted { lhs, rhs in
1631                if lhs.status != rhs.status {
1632                    return lhs.status.rawValue < rhs.status.rawValue
1633                }
1634                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
1635            },
1636            generatedAt: Date()
1637        )
1638        latestBatchSweepSummary = summary
1639
1640        if notificationsAuthorized {
1641            Task {
1642                await LocalNotificationService.shared.notifySweepComplete(summary: summary)
1643            }
1644        }
1645    }
1646
1647    private func updateBatchResult(
1648        domain: String,
1649        status: BatchLookupStatus,
1650        quickStatus: String,
1651        entry: HistoryEntry?,
1652        resultSource: LookupResultSource = .live,
1653        errorMessage: String?
1654    ) {
1655        guard let index = batchResults.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1656            return
1657        }
1658
1659        batchResults[index] = BatchLookupResult(
1660            id: batchResults[index].id,
1661            domain: domain,
1662            historyEntryID: entry?.id,
1663            resultSource: resultSource,
1664            availability: entry?.availabilityResult?.status,
1665            primaryIP: entry?.primaryIP,
1666            quickStatus: quickStatus,
1667            summaryMessage: entry?.changeSummary?.message,
1668            changeSeverity: entry?.changeSummary?.severity,
1669            certificateWarningLevel: entry.map { DomainDiffService.certificateWarningLevel(for: $0.snapshot) } ?? batchResults[index].certificateWarningLevel,
1670            timestamp: entry?.timestamp ?? Date(),
1671            status: status,
1672            errorMessage: errorMessage
1673        )
1674    }
1675
1676    private func clearLookupState() {
1677        dnsSections = []
1678        dnsError = nil
1679        dnsLoading = false
1680        availabilityResult = nil
1681        availabilityLoading = false
1682        suggestions = []
1683        suggestionsLoading = false
1684        sslInfo = nil
1685        sslError = nil
1686        sslLoading = false
1687        hstsPreloaded = nil
1688        hstsLoading = false
1689        httpHeaders = []
1690        httpSecurityGrade = nil
1691        httpStatusCode = nil
1692        httpResponseTimeMs = nil
1693        httpProtocol = nil
1694        http3Advertised = false
1695        httpHeadersError = nil
1696        httpHeadersLoading = false
1697        reachabilityResults = []
1698        reachabilityError = nil
1699        reachabilityLoading = false
1700        ipGeolocation = nil
1701        ipGeolocationError = nil
1702        ipGeolocationLoading = false
1703        emailSecurity = nil
1704        emailSecurityError = nil
1705        emailSecurityLoading = false
1706        ownershipResult = nil
1707        ownershipError = nil
1708        ownershipLoading = false
1709        ptrRecord = nil
1710        ptrError = nil
1711        ptrLoading = false
1712        redirectChain = []
1713        redirectChainError = nil
1714        redirectChainLoading = false
1715        subdomains = []
1716        subdomainsError = nil
1717        subdomainsLoading = false
1718        portScanResults = []
1719        portScanError = nil
1720        portScanLoading = false
1721        customPortResults = []
1722        customPortScanError = nil
1723        customPortScanLoading = false
1724        currentHistoryEntryID = nil
1725        currentSnapshotTimestamp = Date()
1726        currentResultSource = .live
1727        currentCachedSections = []
1728        currentStatusMessage = nil
1729    }
1730
1731    private func setAllLoadingStates(_ loading: Bool) {
1732        dnsLoading = loading
1733        availabilityLoading = loading
1734        suggestionsLoading = loading
1735        sslLoading = loading
1736        hstsLoading = loading
1737        httpHeadersLoading = loading
1738        reachabilityLoading = loading
1739        ipGeolocationLoading = loading
1740        emailSecurityLoading = loading
1741        ownershipLoading = loading
1742        ptrLoading = loading
1743        redirectChainLoading = loading
1744        subdomainsLoading = loading
1745        portScanLoading = loading
1746    }
1747
1748    private func primaryIPAddress(from sections: [DNSSection]) -> String? {
1749        sections.first(where: { $0.recordType == .A })?.records.first?.value
1750    }
1751
1752    private func isCurrentLookup(_ lookupID: UUID) -> Bool {
1753        activeLookupID == lookupID
1754    }
1755
1756    func recentSnapshots(for trackedDomain: TrackedDomain, limit: Int = 6) -> [HistoryEntry] {
1757        history
1758            .filter { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
1759            .sorted { $0.timestamp > $1.timestamp }
1760            .prefix(limit)
1761            .map { $0 }
1762    }
1763
1764    func latestSnapshots(for domains: [TrackedDomain]) -> [HistoryEntry] {
1765        domains.compactMap { trackedDomain in
1766            recentSnapshots(for: trackedDomain, limit: 1).first
1767        }
1768    }
1769
1770    func diffSectionsForLatestSnapshots(of trackedDomain: TrackedDomain) -> [DomainDiffSection] {
1771        let snapshots = recentSnapshots(for: trackedDomain, limit: 2)
1772        guard snapshots.count == 2 else { return [] }
1773        return DomainDiffService.diff(from: snapshots[1].snapshot, to: snapshots[0].snapshot)
1774    }
1775
1776    func latestChangeSummary(for trackedDomain: TrackedDomain) -> DomainChangeSummary? {
1777        trackedDomain.lastChangeSummary ?? recentSnapshots(for: trackedDomain, limit: 1).first?.changeSummary
1778    }
1779
1780    func comparisonSnapshot(for entry: HistoryEntry) -> LookupSnapshot? {
1781        let siblings = history.filter { candidate in
1782            if let trackedDomainID = entry.trackedDomainID {
1783                return candidate.trackedDomainID == trackedDomainID && candidate.id != entry.id
1784            }
1785            return candidate.domain.caseInsensitiveCompare(entry.domain) == .orderedSame && candidate.id != entry.id
1786        }
1787        .sorted { $0.timestamp > $1.timestamp }
1788
1789        return siblings.first?.snapshot
1790    }
1791
1792    func historyEntry(for batchResult: BatchLookupResult) -> HistoryEntry? {
1793        guard let historyEntryID = batchResult.historyEntryID else { return nil }
1794        return history.first(where: { $0.id == historyEntryID })
1795    }
1796
1797    private func exportSnapshots(for domains: [TrackedDomain]) -> [LookupSnapshot] {
1798        let latestEntries = latestSnapshots(for: domains)
1799
1800        return domains.map { trackedDomain in
1801            if let entry = latestEntries.first(where: { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }) {
1802                return entry.snapshot
1803            }
1804            return placeholderSnapshot(for: trackedDomain)
1805        }
1806    }
1807
1808    private func currentBatchReports() -> [DomainReport] {
1809        currentBatchResultEntries.map(report(for:))
1810    }
1811
1812    private func reports(for domains: [TrackedDomain]) -> [DomainReport] {
1813        let latestEntries = latestSnapshots(for: domains)
1814
1815        return domains.map { trackedDomain in
1816            if let entry = latestEntries.first(where: {
1817                $0.trackedDomainID == trackedDomain.id ||
1818                $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame
1819            }) {
1820                return report(for: entry)
1821            }
1822
1823            return reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
1824        }
1825    }
1826
1827    private func report(for entry: HistoryEntry) -> DomainReport {
1828        reportBuilder.build(from: entry, previousSnapshot: comparisonSnapshot(for: entry))
1829    }
1830
1831    private func placeholderSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot {
1832        LookupSnapshot(
1833            historyEntryID: trackedDomain.lastSnapshotID,
1834            domain: trackedDomain.domain,
1835            timestamp: trackedDomain.updatedAt,
1836            trackedDomainID: trackedDomain.id,
1837            resolverDisplayName: resolverDisplayName,
1838            resolverURLString: resolverURLString,
1839            totalLookupDurationMs: nil,
1840            dnsSections: [],
1841            dnsError: nil,
1842            availabilityResult: DomainAvailabilityResult(domain: trackedDomain.domain, status: trackedDomain.lastKnownAvailability ?? .unknown),
1843            suggestions: [],
1844            sslInfo: nil,
1845            sslError: nil,
1846            hstsPreloaded: nil,
1847            httpHeaders: [],
1848            httpSecurityGrade: nil,
1849            httpStatusCode: nil,
1850            httpResponseTimeMs: nil,
1851            httpProtocol: nil,
1852            http3Advertised: false,
1853            httpHeadersError: nil,
1854            reachabilityResults: [],
1855            reachabilityError: nil,
1856            ipGeolocation: nil,
1857            ipGeolocationError: nil,
1858            emailSecurity: nil,
1859            emailSecurityError: nil,
1860            ownership: nil,
1861            ownershipError: nil,
1862            ptrRecord: nil,
1863            ptrError: nil,
1864            redirectChain: [],
1865            redirectChainError: nil,
1866            subdomains: [],
1867            subdomainsError: nil,
1868            portScanResults: [],
1869            portScanError: nil,
1870            changeSummary: trackedDomain.lastChangeSummary,
1871            resultSource: .snapshot,
1872            cachedSections: [],
1873            statusMessage: nil
1874        )
1875    }
1876
1877    private static func loadTrackedDomains() -> [TrackedDomain] {
1878        let defaults = UserDefaults.standard
1879        let decoder = JSONDecoder()
1880
1881        if let data = defaults.data(forKey: trackedDomainsKey),
1882           let domains = try? decoder.decode([TrackedDomain].self, from: data) {
1883            return deduplicatedTrackedDomains(domains)
1884        }
1885
1886        if let legacyData = defaults.data(forKey: legacyWatchedDomainsKey),
1887           let legacyDomains = try? decoder.decode([WatchedDomain].self, from: legacyData) {
1888            return deduplicatedTrackedDomains(
1889                legacyDomains.map {
1890                    TrackedDomain(
1891                        id: $0.id,
1892                        domain: $0.domain.lowercased(),
1893                        createdAt: $0.createdAt,
1894                        updatedAt: $0.createdAt,
1895                        lastKnownAvailability: $0.lastKnownAvailability
1896                    )
1897                }
1898            )
1899        }
1900
1901        return []
1902    }
1903
1904    private static func deduplicatedTrackedDomains(_ domains: [TrackedDomain]) -> [TrackedDomain] {
1905        var seen = Set<String>()
1906        return domains.filter { domain in
1907            let key = domain.domain.lowercased()
1908            return seen.insert(key).inserted
1909        }
1910    }
1911
1912    private func historySortPredicate(lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
1913        switch historySortOption {
1914        case .newest:
1915            return lhs.timestamp > rhs.timestamp
1916        case .oldest:
1917            return lhs.timestamp < rhs.timestamp
1918        case .domain:
1919            let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
1920            if domainOrder != .orderedSame {
1921                return domainOrder == .orderedAscending
1922            }
1923            return lhs.timestamp > rhs.timestamp
1924        }
1925    }
1926
1927    private func sortedTrackedDomains(from domains: [TrackedDomain], using sortOption: WatchlistSortOption) -> [TrackedDomain] {
1928        domains.sorted { lhs, rhs in
1929            switch sortOption {
1930            case .pinned:
1931                if lhs.isPinned != rhs.isPinned {
1932                    return lhs.isPinned && !rhs.isPinned
1933                }
1934                if lhs.updatedAt != rhs.updatedAt {
1935                    return lhs.updatedAt > rhs.updatedAt
1936                }
1937                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
1938            case .recentlyUpdated:
1939                if lhs.updatedAt != rhs.updatedAt {
1940                    return lhs.updatedAt > rhs.updatedAt
1941                }
1942                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
1943            case .alphabetical:
1944                let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
1945                if domainOrder != .orderedSame {
1946                    return domainOrder == .orderedAscending
1947                }
1948                return lhs.updatedAt > rhs.updatedAt
1949            }
1950        }
1951    }
1952
1953    static func summaryFields(from snapshot: LookupSnapshot) -> [SummaryFieldViewData] {
1954        [
1955            SummaryFieldViewData(label: "Domain", value: snapshot.domain.nonEmpty ?? "Unavailable", tone: .primary),
1956            SummaryFieldViewData(label: "Primary IP", value: primaryIPAddress(from: snapshot) ?? "Unavailable", tone: .primary),
1957            SummaryFieldViewData(label: "HTTPS", value: httpsSummary(from: snapshot), tone: httpsSummaryTone(from: snapshot)),
1958            SummaryFieldViewData(label: "Certificate", value: certificateStatusLabel(from: snapshot), tone: certificateStatusTone(from: snapshot)),
1959            SummaryFieldViewData(label: "Redirect", value: finalRedirectTarget(from: snapshot) ?? "Unavailable", tone: .secondary),
1960            SummaryFieldViewData(label: "Source", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot))
1961        ]
1962    }
1963
1964    static func domainRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1965        var rows = [
1966            InfoRowViewData(label: "Domain", value: snapshot.domain, tone: .primary),
1967            InfoRowViewData(label: "Resolver", value: snapshot.resolverDisplayName, tone: .secondary),
1968            InfoRowViewData(label: snapshot.statusMessage == nil ? "Result" : "Snapshot", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot)),
1969            InfoRowViewData(label: "Lookup Duration", value: durationLabel(snapshot.totalLookupDurationMs), tone: .secondary)
1970        ]
1971        rows.insert(
1972            InfoRowViewData(
1973                label: "Availability",
1974                value: availabilityLabel(snapshot.availabilityResult?.status),
1975                tone: availabilityTone(snapshot.availabilityResult?.status)
1976            ),
1977            at: 1
1978        )
1979        if let certificateStatus = certificateBadgeLabel(from: snapshot) {
1980            rows.insert(
1981                InfoRowViewData(
1982                    label: "Certificate",
1983                    value: certificateStatus,
1984                    tone: certificateStatusTone(from: snapshot)
1985                ),
1986                at: 2
1987            )
1988        }
1989        return rows
1990    }
1991
1992    static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
1993        snapshot.suggestions.map {
1994            DomainSuggestionViewData(
1995                id: $0.id,
1996                domain: $0.domain,
1997                status: availabilityLabel($0.status),
1998                tone: availabilityTone($0.status)
1999            )
2000        }
2001    }
2002
2003    static func dnsRows(from snapshot: LookupSnapshot) -> [DNSRecordSectionViewData] {
2004        snapshot.dnsSections.map { section in
2005            DNSRecordSectionViewData(
2006                title: section.recordType.rawValue,
2007                rows: section.records.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary) },
2008                wildcardRows: section.wildcardRecords.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary) },
2009                wildcardTitle: section.wildcardRecords.isEmpty ? nil : "*.\(snapshot.domain)",
2010                message: section.error.map { SectionMessageViewData(text: $0, isError: true) } ??
2011                    ((section.records.isEmpty && section.wildcardRecords.isEmpty) ? SectionMessageViewData(text: "No records found", isError: false) : nil)
2012            )
2013        }
2014    }
2015
2016    static func dnssecLabel(from snapshot: LookupSnapshot) -> String? {
2017        guard let signed = snapshot.dnsSections.compactMap(\.dnssecSigned).first else { return nil }
2018        return "Resolver-reported DNSSEC (not full validation): \(signed ? "Yes" : "No")"
2019    }
2020
2021    static func ptrMessage(from snapshot: LookupSnapshot) -> SectionMessageViewData? {
2022        if let ptrRecord = snapshot.ptrRecord {
2023            return SectionMessageViewData(text: ptrRecord, isError: false)
2024        }
2025        if let ptrError = snapshot.ptrError {
2026            return SectionMessageViewData(text: ptrError, isError: ptrError != "No A record available" && ptrError != "No PTR record found")
2027        }
2028        return nil
2029    }
2030
2031    static func webCertificateRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
2032        guard let sslInfo = snapshot.sslInfo else { return [] }
2033        var rows = [
2034            InfoRowViewData(label: "Common Name", value: sslInfo.commonName, tone: .primary),
2035            InfoRowViewData(label: "Issuer", value: sslInfo.issuer, tone: .primary),
2036            InfoRowViewData(label: "Valid From", value: certificateDateFormatter.string(from: sslInfo.validFrom), tone: .secondary),
2037            InfoRowViewData(label: "Valid Until", value: certificateDateFormatter.string(from: sslInfo.validUntil), tone: .secondary),
2038            InfoRowViewData(label: "Days Until Expiry", value: "\(sslInfo.daysUntilExpiry)", tone: certificateTone(daysRemaining: sslInfo.daysUntilExpiry)),
2039            InfoRowViewData(label: "Chain Depth", value: "\(sslInfo.chainDepth)", tone: .secondary)
2040        ]
2041        if let tlsVersion = sslInfo.tlsVersion {
2042            rows.append(InfoRowViewData(label: "TLS Version", value: tlsVersion, tone: .secondary))
2043        }
2044        if let cipherSuite = sslInfo.cipherSuite {
2045            rows.append(InfoRowViewData(label: "Cipher Suite", value: cipherSuite, tone: .secondary))
2046        }
2047        if let hstsPreloaded = snapshot.hstsPreloaded {
2048            rows.append(InfoRowViewData(label: "HSTS Preload", value: hstsPreloaded ? "Preloaded" : "Not preloaded", tone: hstsPreloaded ? .success : .secondary))
2049        }
2050        return rows
2051    }
2052
2053    static func webResponseRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
2054        var rows: [InfoRowViewData] = []
2055        if let httpStatusCode = snapshot.httpStatusCode {
2056            rows.append(InfoRowViewData(label: "Status", value: "\(httpStatusCode)", tone: .primary))
2057        }
2058        if let httpResponseTimeMs = snapshot.httpResponseTimeMs {
2059            rows.append(InfoRowViewData(label: "Response Time", value: "\(httpResponseTimeMs) ms", tone: .secondary))
2060        }
2061        if let httpProtocol = snapshot.httpProtocol {
2062            rows.append(InfoRowViewData(label: "Protocol", value: httpProtocol, tone: .secondary))
2063        }
2064        if let httpSecurityGrade = snapshot.httpSecurityGrade {
2065            rows.append(InfoRowViewData(label: "Security Grade", value: httpSecurityGrade, tone: securityGradeTone(httpSecurityGrade)))
2066        }
2067        if snapshot.http3Advertised {
2068            rows.append(InfoRowViewData(label: "HTTP/3", value: "Advertised", tone: .secondary))
2069        }
2070        return rows
2071    }
2072
2073    static func redirectRows(from snapshot: LookupSnapshot) -> [RedirectHopViewData] {
2074        snapshot.redirectChain.map {
2075            RedirectHopViewData(
2076                stepLabel: "\($0.stepNumber)",
2077                statusCode: "\($0.statusCode)",
2078                url: $0.url,
2079                isFinal: $0.isFinal
2080            )
2081        }
2082    }
2083
2084    static func emailRows(from snapshot: LookupSnapshot) -> [EmailRowViewData] {
2085        guard let emailSecurity = snapshot.emailSecurity else { return [] }
2086        return [
2087            EmailRowViewData(label: "SPF", status: emailSecurity.spf.found ? "Present" : "Missing", statusTone: emailSecurity.spf.found ? .success : .warning, detail: emailSecurity.spf.value ?? "No record found", auxiliaryDetail: nil),
2088            EmailRowViewData(label: "DMARC", status: emailSecurity.dmarc.found ? "Present" : "Missing", statusTone: emailSecurity.dmarc.found ? .success : .warning, detail: emailSecurity.dmarc.value ?? "No record found", auxiliaryDetail: nil),
2089            EmailRowViewData(label: "DKIM", status: emailSecurity.dkim.found ? "Present" : "Missing", statusTone: emailSecurity.dkim.found ? .success : .warning, detail: emailSecurity.dkim.value ?? "No record found", auxiliaryDetail: emailSecurity.dkim.matchedSelector.map { "Selector: \($0)" }),
2090            EmailRowViewData(label: "MTA-STS", status: emailSecurity.mtaSts?.txtFound == true ? "Present" : "Missing", statusTone: emailSecurity.mtaSts?.txtFound == true ? .success : .warning, detail: emailSecurity.mtaSts?.policyMode ?? (emailSecurity.mtaSts?.txtFound == true ? "Policy unavailable" : "No record found"), auxiliaryDetail: nil),
2091            EmailRowViewData(label: "BIMI", status: emailSecurity.bimi.found ? "Present" : "Missing", statusTone: emailSecurity.bimi.found ? .success : .warning, detail: emailSecurity.bimi.value ?? "No record found", auxiliaryDetail: nil)
2092        ]
2093    }
2094
2095    static func ownershipRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
2096        let ownership = snapshot.ownership
2097
2098        return [
2099            InfoRowViewData(label: "Registrar", value: ownership?.registrar ?? "Unavailable", tone: ownership?.registrar == nil ? .secondary : .primary),
2100            InfoRowViewData(label: "Registered", value: ownership?.createdDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.createdDate == nil ? .secondary : .primary),
2101            InfoRowViewData(label: "Expires", value: ownership?.expirationDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.expirationDate == nil ? .secondary : .primary),
2102            InfoRowViewData(label: "Status", value: ownership?.status.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.status.isEmpty == false ? .primary : .secondary),
2103            InfoRowViewData(label: "Nameservers", value: ownership?.nameservers.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.nameservers.isEmpty == false ? .primary : .secondary),
2104            InfoRowViewData(label: "Abuse Contact", value: ownership?.abuseEmail ?? "Unavailable", tone: ownership?.abuseEmail == nil ? .secondary : .primary)
2105        ]
2106    }
2107
2108    static func subdomainRows(from snapshot: LookupSnapshot) -> [SubdomainRowViewData] {
2109        snapshot.subdomains.map { subdomain in
2110            SubdomainRowViewData(
2111                hostname: subdomain.hostname,
2112                isInteresting: isInterestingSubdomain(subdomain.hostname)
2113            )
2114        }
2115    }
2116
2117    static func reachabilityRows(from snapshot: LookupSnapshot) -> [ReachabilityRowViewData] {
2118        snapshot.reachabilityResults.map {
2119            ReachabilityRowViewData(
2120                portLabel: "Port \($0.port)",
2121                latencyLabel: $0.latencyMs.map { "\($0) ms" } ?? "—",
2122                statusLabel: $0.reachable ? "Reachable" : "Unreachable",
2123                statusTone: $0.reachable ? .success : .failure
2124            )
2125        }
2126    }
2127
2128    static func locationRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
2129        guard let ipGeolocation = snapshot.ipGeolocation else { return [] }
2130        var rows = [InfoRowViewData(label: "IP", value: ipGeolocation.ip, tone: .primary)]
2131        if let org = ipGeolocation.org {
2132            rows.append(InfoRowViewData(label: "Org / ISP", value: org, tone: .secondary))
2133        }
2134        let location = [ipGeolocation.city, ipGeolocation.region, ipGeolocation.country_name].compactMap { $0 }.joined(separator: ", ")
2135        if !location.isEmpty {
2136            rows.append(InfoRowViewData(label: "Location", value: location, tone: .secondary))
2137        }
2138        if let latitude = ipGeolocation.latitude, let longitude = ipGeolocation.longitude {
2139            rows.append(InfoRowViewData(label: "Coordinates", value: "\(latitude), \(longitude)", tone: .secondary))
2140        }
2141        return rows
2142    }
2143
2144    static func portRows(from snapshot: LookupSnapshot, kind: PortScanKind) -> [PortScanRowViewData] {
2145        snapshot.portScanResults
2146            .filter { $0.kind == kind }
2147            .map {
2148                PortScanRowViewData(
2149                    portLabel: "\($0.port)",
2150                    service: $0.service,
2151                    statusLabel: $0.open ? "Open" : "Closed",
2152                    statusTone: $0.open ? .success : .secondary,
2153                    banner: $0.banner,
2154                    durationLabel: $0.durationMs.map { "\($0) ms" }
2155                )
2156            }
2157    }
2158
2159    static func formatBatchExportText(
2160        title: String,
2161        entries: [(snapshot: LookupSnapshot, trackedDomain: TrackedDomain?, changeSummary: DomainChangeSummary?, diffSections: [DomainDiffSection])]
2162    ) -> String {
2163        guard !entries.isEmpty else {
2164            return "\(title)\nNo results available."
2165        }
2166
2167        var lines = [title, String(repeating: "=", count: title.count), ""]
2168        for (index, entry) in entries.enumerated() {
2169            if index > 0 {
2170                lines.append("")
2171                lines.append(String(repeating: "=", count: 48))
2172                lines.append("")
2173            }
2174
2175            lines.append(
2176                formatExportText(
2177                    from: entry.snapshot,
2178                    trackedDomain: entry.trackedDomain,
2179                    changeSummary: entry.changeSummary,
2180                    diffSections: entry.diffSections
2181                )
2182            )
2183        }
2184        return lines.joined(separator: "\n")
2185    }
2186
2187    static func formatCSV(from snapshots: [LookupSnapshot]) -> String {
2188        let headers = [
2189            "domain",
2190            "availability",
2191            "primary_ip",
2192            "redirect_target",
2193            "tls_status",
2194            "http_status_grade",
2195            "email_security_summary",
2196            "registrar",
2197            "ownership_expires",
2198            "ownership_status",
2199            "ownership_nameservers",
2200            "subdomain_count",
2201            "subdomains",
2202            "last_updated"
2203        ]
2204
2205        let rows = snapshots.map { snapshot in
2206            [
2207                snapshot.domain,
2208                availabilityLabel(snapshot.availabilityResult?.status),
2209                primaryIPAddress(from: snapshot) ?? "",
2210                finalRedirectTarget(from: snapshot) ?? "",
2211                httpsSummary(from: snapshot),
2212                httpStatusGradeSummary(from: snapshot),
2213                emailSummary(from: snapshot),
2214                snapshot.ownership?.registrar ?? "",
2215                snapshot.ownership?.expirationDate.map(csvDateFormatter.string(from:)) ?? "",
2216                snapshot.ownership?.status.joined(separator: " | ") ?? "",
2217                snapshot.ownership?.nameservers.joined(separator: " | ") ?? "",
2218                "\(snapshot.subdomains.count)",
2219                snapshot.subdomains.map(\.hostname).joined(separator: " | "),
2220                csvDateFormatter.string(from: snapshot.timestamp)
2221            ]
2222        }
2223
2224        return ([headers] + rows)
2225            .map { row in row.map(csvEscaped).joined(separator: ",") }
2226            .joined(separator: "\n")
2227    }
2228
2229    static func formatExportText(
2230        from snapshot: LookupSnapshot,
2231        trackedDomain: TrackedDomain?,
2232        changeSummary: DomainChangeSummary?,
2233        diffSections: [DomainDiffSection]
2234    ) -> String {
2235        let exportDateFormatter = DateFormatter()
2236        exportDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
2237
2238        var lines: [String] = [
2239            "DomainDig Export",
2240            "Domain: \(snapshot.domain)",
2241            "Date: \(exportDateFormatter.string(from: snapshot.timestamp))",
2242            "Mode: \(snapshot.statusMessage ?? snapshot.resultSource.label)",
2243            "Resolver: \(snapshot.resolverDisplayName)",
2244            "Lookup Duration: \(durationLabel(snapshot.totalLookupDurationMs))",
2245            "Tracked: \(trackedDomain == nil ? "No" : "Yes")"
2246        ]
2247
2248        if let note = trackedDomain?.note?.nilIfEmpty {
2249            lines.append("Tracking Note: \(note)")
2250        }
2251
2252        func appendSection(_ title: String, body: () -> Void) {
2253            lines.append("")
2254            lines.append(title)
2255            lines.append(String(repeating: "-", count: title.count))
2256            body()
2257        }
2258
2259        appendSection("Summary") {
2260            for item in summaryFields(from: snapshot) {
2261                lines.append("  \(item.label): \(item.value)")
2262            }
2263            if let changeSummary {
2264                lines.append("  Change Summary: \(changeSummary.message)")
2265                lines.append("  Severity: \(changeSummary.severity.title)")
2266                lines.append("  Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
2267                lines.append("  Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
2268            }
2269        }
2270
2271        appendSection("Tracking") {
2272            if let trackedDomain {
2273                lines.append("  Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
2274                lines.append("  Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
2275                lines.append("  Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
2276                if let note = trackedDomain.note?.nilIfEmpty {
2277                    lines.append("  Note: \(note)")
2278                }
2279            } else {
2280                lines.append("  This domain is not currently tracked.")
2281            }
2282        }
2283
2284        appendSection("Diff Summary") {
2285            if diffSections.isEmpty {
2286                lines.append("  No comparison available")
2287            } else {
2288                for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
2289                    lines.append("  \(section.title)")
2290                    for item in section.items where item.changeType != .unchanged {
2291                        lines.append("    [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
2292                    }
2293                }
2294            }
2295        }
2296
2297        appendSection("Domain") {
2298            for row in domainRows(from: snapshot) {
2299                lines.append("  \(row.label): \(row.value)")
2300            }
2301            if snapshot.suggestions.isEmpty {
2302                lines.append("  Suggestions: None")
2303            } else {
2304                lines.append("  Suggestions:")
2305                for suggestion in snapshot.suggestions {
2306                    lines.append("    \(suggestion.domain): \(availabilityLabel(suggestion.status))")
2307                }
2308            }
2309        }
2310
2311        appendSection("Ownership") {
2312            for row in ownershipRows(from: snapshot) {
2313                lines.append("  \(row.label): \(row.value)")
2314            }
2315            if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
2316                lines.append("  Source: \(ownershipError)")
2317            }
2318            if !DataAccessService.hasAccess(to: .ownershipHistory) {
2319                lines.append("  Ownership history (coming soon)")
2320            }
2321        }
2322
2323        appendSection("Subdomains") {
2324            lines.append("  Count: \(snapshot.subdomains.count)")
2325            if snapshot.subdomains.isEmpty {
2326                lines.append("  \(snapshot.subdomainsError ?? "No passive subdomains found")")
2327            } else {
2328                for subdomain in subdomainRows(from: snapshot) {
2329                    let marker = subdomain.isInteresting ? " [interesting]" : ""
2330                    lines.append("  \(subdomain.hostname)\(marker)")
2331                }
2332            }
2333            if !DataAccessService.hasAccess(to: .extendedSubdomains) {
2334                lines.append("  Extended subdomain discovery (Data+)")
2335            }
2336        }
2337
2338        appendSection("DNS") {
2339            if let dnsError = snapshot.dnsError {
2340                lines.append("  Error: \(dnsError)")
2341            }
2342            if let dnssecLabel = dnssecLabel(from: snapshot) {
2343                lines.append("  \(dnssecLabel)")
2344            }
2345            for section in dnsRows(from: snapshot) {
2346                lines.append("  \(section.title)")
2347                if let message = section.message {
2348                    lines.append("    \(message.isError ? "Error" : "Info"): \(message.text)")
2349                }
2350                for row in section.rows {
2351                    lines.append("    \(row.value) (\(row.label))")
2352                }
2353                if let wildcardTitle = section.wildcardTitle {
2354                    lines.append("    \(wildcardTitle)")
2355                    for row in section.wildcardRows {
2356                        lines.append("      \(row.value) (\(row.label))")
2357                    }
2358                }
2359            }
2360            if let ptrRecord = snapshot.ptrRecord {
2361                lines.append("  PTR: \(ptrRecord)")
2362            } else if let ptrError = snapshot.ptrError {
2363                lines.append("  PTR Error: \(ptrError)")
2364            }
2365        }
2366
2367        appendSection("Web") {
2368            if let sslError = snapshot.sslError {
2369                lines.append("  TLS Error: \(sslError)")
2370            } else {
2371                for row in webCertificateRows(from: snapshot) {
2372                    lines.append("  \(row.label): \(row.value)")
2373                }
2374            }
2375
2376            if let httpHeadersError = snapshot.httpHeadersError {
2377                lines.append("  Headers Error: \(httpHeadersError)")
2378            } else {
2379                for row in webResponseRows(from: snapshot) {
2380                    lines.append("  \(row.label): \(row.value)")
2381                }
2382                if snapshot.httpHeaders.isEmpty {
2383                    lines.append("  Headers: No headers returned")
2384                } else {
2385                    lines.append("  Headers:")
2386                    for header in snapshot.httpHeaders {
2387                        lines.append("    \(header.name): \(header.value)")
2388                    }
2389                }
2390            }
2391
2392            if let redirectChainError = snapshot.redirectChainError {
2393                lines.append("  Redirect Error: \(redirectChainError)")
2394            } else if snapshot.redirectChain.isEmpty {
2395                lines.append("  Redirects: No redirect data available")
2396            } else {
2397                lines.append("  Redirects:")
2398                for hop in redirectRows(from: snapshot) {
2399                    lines.append("    \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
2400                }
2401            }
2402        }
2403
2404        appendSection("Email") {
2405            if let emailSecurityError = snapshot.emailSecurityError {
2406                lines.append("  Error: \(emailSecurityError)")
2407            } else if emailRows(from: snapshot).isEmpty {
2408                lines.append("  No email security records found")
2409            } else {
2410                for row in emailRows(from: snapshot) {
2411                    lines.append("  \(row.label): \(row.status)")
2412                    lines.append("    \(row.detail)")
2413                    if let auxiliaryDetail = row.auxiliaryDetail {
2414                        lines.append("    \(auxiliaryDetail)")
2415                    }
2416                }
2417            }
2418        }
2419
2420        appendSection("Network") {
2421            if let reachabilityError = snapshot.reachabilityError {
2422                lines.append("  Reachability Error: \(reachabilityError)")
2423            } else if reachabilityRows(from: snapshot).isEmpty {
2424                lines.append("  Reachability: No results")
2425            } else {
2426                lines.append("  Reachability:")
2427                for row in reachabilityRows(from: snapshot) {
2428                    lines.append("    \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
2429                }
2430            }
2431
2432            if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
2433                lines.append("  Location Error: \(ipGeolocationError)")
2434            } else if locationRows(from: snapshot).isEmpty {
2435                lines.append("  Location: No data")
2436            } else {
2437                lines.append("  Location:")
2438                for row in locationRows(from: snapshot) {
2439                    lines.append("    \(row.label): \(row.value)")
2440                }
2441            }
2442
2443            if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
2444                lines.append("  Port Scan Error: \(portScanError)")
2445            }
2446
2447            lines.append("  Standard Ports:")
2448            let standardRows = portRows(from: snapshot, kind: .standard)
2449            if standardRows.isEmpty {
2450                lines.append("    No results")
2451            } else {
2452                for row in standardRows {
2453                    lines.append("    \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
2454                    if let banner = row.banner {
2455                        lines.append("      Banner: \(banner)")
2456                    }
2457                }
2458            }
2459
2460            lines.append("  Custom Ports:")
2461            let customRows = portRows(from: snapshot, kind: .custom)
2462            if customRows.isEmpty {
2463                lines.append("    No results")
2464            } else {
2465                for row in customRows {
2466                    lines.append("    \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
2467                    if let banner = row.banner {
2468                        lines.append("      Banner: \(banner)")
2469                    }
2470                }
2471            }
2472        }
2473
2474        return lines.joined(separator: "\n")
2475    }
2476
2477    private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
2478        snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
2479    }
2480
2481    private static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
2482        snapshot.redirectChain.last?.url
2483    }
2484
2485    private static func httpStatusGradeSummary(from snapshot: LookupSnapshot) -> String {
2486        let parts = [snapshot.httpStatusCode.map(String.init), snapshot.httpSecurityGrade].compactMap { $0 }
2487        if !parts.isEmpty {
2488            return parts.joined(separator: " / ")
2489        }
2490        return snapshot.httpHeadersError ?? "Unavailable"
2491    }
2492
2493    private static func httpsSummary(from snapshot: LookupSnapshot) -> String {
2494        if snapshot.sslInfo != nil {
2495            return "Valid"
2496        }
2497        if let sslError = snapshot.sslError {
2498            return sslError.localizedCaseInsensitiveContains("certificate") ? "Invalid" : "Failed"
2499        }
2500        return "Unavailable"
2501    }
2502
2503    private static func httpsSummaryTone(from snapshot: LookupSnapshot) -> ResultTone {
2504        if snapshot.sslInfo != nil {
2505            return .success
2506        }
2507        return snapshot.sslError == nil ? .secondary : .failure
2508    }
2509
2510    private static func emailSummary(from snapshot: LookupSnapshot) -> String {
2511        guard let emailSecurity = snapshot.emailSecurity else {
2512            return snapshot.emailSecurityError ?? "Unavailable"
2513        }
2514        return "SPF \(emailSecurity.spf.found ? "Yes" : "No") / DMARC \(emailSecurity.dmarc.found ? "Yes" : "No")"
2515    }
2516
2517    private static func certificateStatusLabel(from snapshot: LookupSnapshot) -> String {
2518        guard let sslInfo = snapshot.sslInfo else {
2519            return snapshot.sslError ?? "Unavailable"
2520        }
2521
2522        switch DomainDiffService.certificateWarningLevel(for: snapshot) {
2523        case .critical:
2524            return "Critical (\(sslInfo.daysUntilExpiry)d)"
2525        case .warning:
2526            return "Warning (\(sslInfo.daysUntilExpiry)d)"
2527        case .none:
2528            return "Healthy (\(sslInfo.daysUntilExpiry)d)"
2529        }
2530    }
2531
2532    private static func certificateBadgeLabel(from snapshot: LookupSnapshot) -> String? {
2533        guard snapshot.sslInfo != nil else { return nil }
2534        return certificateStatusLabel(from: snapshot)
2535    }
2536
2537    private static func certificateStatusTone(from snapshot: LookupSnapshot) -> ResultTone {
2538        guard let daysRemaining = snapshot.sslInfo?.daysUntilExpiry else {
2539            return snapshot.sslError == nil ? .secondary : .failure
2540        }
2541        return certificateTone(daysRemaining: daysRemaining)
2542    }
2543
2544    private static func certificateTone(daysRemaining: Int) -> ResultTone {
2545        if daysRemaining < 14 {
2546            return .failure
2547        }
2548        if daysRemaining < 30 {
2549            return .warning
2550        }
2551        return .success
2552    }
2553
2554    private static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
2555        switch status {
2556        case .available:
2557            return "Available"
2558        case .registered:
2559            return "Registered"
2560        case .unknown, .none:
2561            return "Unknown"
2562        }
2563    }
2564
2565    private static func availabilityTone(_ status: DomainAvailabilityStatus?) -> ResultTone {
2566        switch status {
2567        case .available:
2568            return .success
2569        case .registered:
2570            return .warning
2571        case .unknown, .none:
2572            return .secondary
2573        }
2574    }
2575
2576    private static func sourceTone(for snapshot: LookupSnapshot) -> ResultTone {
2577        if snapshot.statusMessage != nil {
2578            return .warning
2579        }
2580
2581        switch snapshot.resultSource {
2582        case .live:
2583            return .success
2584        case .cached:
2585            return .secondary
2586        case .mixed:
2587            return .warning
2588        case .snapshot:
2589            return .warning
2590        }
2591    }
2592
2593    private static func securityGradeTone(_ grade: String) -> ResultTone {
2594        switch grade {
2595        case "A", "B":
2596            return .success
2597        case "C":
2598            return .warning
2599        case "D", "F":
2600            return .failure
2601        default:
2602            return .secondary
2603        }
2604    }
2605
2606    private static func durationLabel(_ durationMs: Int?) -> String {
2607        durationMs.map { "\($0) ms" } ?? "Unavailable"
2608    }
2609
2610    private static let certificateDateFormatter: DateFormatter = {
2611        let formatter = DateFormatter()
2612        formatter.dateStyle = .medium
2613        formatter.timeStyle = .short
2614        return formatter
2615    }()
2616
2617    private static let ownershipDateFormatter: DateFormatter = {
2618        let formatter = DateFormatter()
2619        formatter.dateStyle = .medium
2620        formatter.timeStyle = .none
2621        return formatter
2622    }()
2623
2624    private static let csvDateFormatter: ISO8601DateFormatter = {
2625        let formatter = ISO8601DateFormatter()
2626        formatter.formatOptions = [.withInternetDateTime]
2627        return formatter
2628    }()
2629
2630    private static func csvEscaped(_ value: String) -> String {
2631        let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
2632        return "\"\(escaped)\""
2633    }
2634
2635    private static func isInterestingSubdomain(_ hostname: String) -> Bool {
2636        let keywords = ["admin", "api", "dev", "staging", "test", "internal"]
2637        let labels = hostname.lowercased().split(separator: ".").map(String.init)
2638        return labels.contains { label in
2639            keywords.contains(where: { label.contains($0) })
2640        }
2641    }
2642}
2643
2644private extension String {
2645    var nonEmpty: String? {
2646        isEmpty ? nil : self
2647    }
2648
2649    var nilIfEmpty: String? {
2650        isEmpty ? nil : self
2651    }
2652}
2653
2654private extension Array where Element == String {
2655    var nilIfEmpty: [String]? {
2656        isEmpty ? nil : self
2657    }
2658}