DomainDig/DomainViewModel.swift

22ecca12b4fe0e0850401754c674632f322d919d
domain-dig/DomainDig/DomainViewModel.swift history · blame · raw

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