DomainDig/DomainViewModel.swift

2e90ee4ceca73d5126118920b486149cb227c4e9
domain-dig/DomainDig/DomainViewModel.swift history · blame · raw

2149 lines · 81265 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 DomainSuggestionViewData: Identifiable {
  76    let id: UUID
  77    let domain: String
  78    let status: String
  79    let tone: ResultTone
  80}
  81
  82struct LookupSnapshot {
  83    let historyEntryID: UUID?
  84    let domain: String
  85    let timestamp: Date
  86    let trackedDomainID: UUID?
  87    let resolverDisplayName: String
  88    let resolverURLString: String
  89    let totalLookupDurationMs: Int?
  90    let dnsSections: [DNSSection]
  91    let dnsError: String?
  92    let availabilityResult: DomainAvailabilityResult?
  93    let suggestions: [DomainSuggestionResult]
  94    let sslInfo: SSLCertificateInfo?
  95    let sslError: String?
  96    let hstsPreloaded: Bool?
  97    let httpHeaders: [HTTPHeader]
  98    let httpSecurityGrade: String?
  99    let httpStatusCode: Int?
 100    let httpResponseTimeMs: Int?
 101    let httpProtocol: String?
 102    let http3Advertised: Bool
 103    let httpHeadersError: String?
 104    let reachabilityResults: [PortReachability]
 105    let reachabilityError: String?
 106    let ipGeolocation: IPGeolocation?
 107    let ipGeolocationError: String?
 108    let emailSecurity: EmailSecurityResult?
 109    let emailSecurityError: String?
 110    let ptrRecord: String?
 111    let ptrError: String?
 112    let redirectChain: [RedirectHop]
 113    let redirectChainError: String?
 114    let portScanResults: [PortScanResult]
 115    let portScanError: String?
 116    let changeSummary: DomainChangeSummary?
 117    let isLive: Bool
 118}
 119
 120extension HistoryEntry {
 121    var snapshot: LookupSnapshot {
 122        LookupSnapshot(
 123            historyEntryID: id,
 124            domain: domain,
 125            timestamp: timestamp,
 126            trackedDomainID: trackedDomainID,
 127            resolverDisplayName: resolverDisplayName,
 128            resolverURLString: resolverURLString,
 129            totalLookupDurationMs: totalLookupDurationMs,
 130            dnsSections: dnsSections,
 131            dnsError: nil,
 132            availabilityResult: availabilityResult,
 133            suggestions: suggestions,
 134            sslInfo: sslInfo,
 135            sslError: sslError,
 136            hstsPreloaded: hstsPreloaded,
 137            httpHeaders: httpHeaders,
 138            httpSecurityGrade: HTTPSecurityGrade.grade(for: httpHeaders).rawValue,
 139            httpStatusCode: nil,
 140            httpResponseTimeMs: nil,
 141            httpProtocol: nil,
 142            http3Advertised: false,
 143            httpHeadersError: httpHeadersError,
 144            reachabilityResults: reachabilityResults,
 145            reachabilityError: reachabilityError,
 146            ipGeolocation: ipGeolocation,
 147            ipGeolocationError: ipGeolocationError,
 148            emailSecurity: emailSecurity,
 149            emailSecurityError: emailSecurityError,
 150            ptrRecord: ptrRecord,
 151            ptrError: ptrError,
 152            redirectChain: redirectChain,
 153            redirectChainError: redirectChainError,
 154            portScanResults: portScanResults,
 155            portScanError: portScanError,
 156            changeSummary: changeSummary,
 157            isLive: false
 158        )
 159    }
 160}
 161
 162@MainActor
 163@Observable
 164final class DomainViewModel {
 165    var domain: String = ""
 166    var bulkInput: String = ""
 167
 168    var dnsSections: [DNSSection] = []
 169    var dnsLoading = false
 170    var dnsError: String?
 171    var availabilityResult: DomainAvailabilityResult?
 172    var availabilityLoading = false
 173    var suggestions: [DomainSuggestionResult] = []
 174    var suggestionsLoading = false
 175
 176    var sslInfo: SSLCertificateInfo?
 177    var sslLoading = false
 178    var sslError: String?
 179    var hstsPreloaded: Bool?
 180    var hstsLoading = false
 181
 182    var httpHeaders: [HTTPHeader] = []
 183    var httpSecurityGrade: String?
 184    var httpStatusCode: Int?
 185    var httpResponseTimeMs: Int?
 186    var httpProtocol: String?
 187    var http3Advertised = false
 188    var httpHeadersLoading = false
 189    var httpHeadersError: String?
 190
 191    var reachabilityResults: [PortReachability] = []
 192    var reachabilityLoading = false
 193    var reachabilityError: String?
 194
 195    var ipGeolocation: IPGeolocation?
 196    var ipGeolocationLoading = false
 197    var ipGeolocationError: String?
 198
 199    var emailSecurity: EmailSecurityResult?
 200    var emailSecurityLoading = false
 201    var emailSecurityError: String?
 202
 203    var ptrRecord: String?
 204    var ptrLoading = false
 205    var ptrError: String?
 206
 207    var redirectChain: [RedirectHop] = []
 208    var redirectChainLoading = false
 209    var redirectChainError: String?
 210
 211    var portScanResults: [PortScanResult] = []
 212    var portScanLoading = false
 213    var portScanError: String?
 214    var customPortResults: [PortScanResult] = []
 215    var customPortScanLoading = false
 216    var customPortScanError: String?
 217
 218    var hasRun = false
 219    private(set) var searchedDomain: String = ""
 220    private(set) var lastLookupDurationMs: Int?
 221    private(set) var currentDiffSections: [DomainDiffSection] = []
 222    private(set) var currentChangeSummary: DomainChangeSummary?
 223    private(set) var refreshingTrackedDomainID: UUID?
 224    private(set) var rerunNavigationToken = UUID()
 225    private(set) var batchResults: [BatchLookupResult] = []
 226    private(set) var batchLookupSource: BatchLookupSource = .manual
 227    private(set) var batchCurrentDomain: String?
 228    private(set) var batchCompletedCount = 0
 229    private(set) var batchTotalCount = 0
 230    private(set) var batchLookupRunning = false
 231
 232    private var lookupTask: Task<Void, Never>?
 233    private var customPortScanTask: Task<Void, Never>?
 234    private var activeLookupID = UUID()
 235    private var lookupStartedAt: Date?
 236
 237    private static let recentSearchesKey = "recentSearches"
 238    private static let maxRecent = 20
 239    var recentSearches: [String] = UserDefaults.standard.stringArray(forKey: recentSearchesKey) ?? []
 240
 241    private static let savedDomainsKey = "savedDomains"
 242    var savedDomains: [String] = UserDefaults.standard.stringArray(forKey: savedDomainsKey) ?? []
 243
 244    private static let trackedDomainsKey = "trackedDomains"
 245    private static let legacyWatchedDomainsKey = "watchedDomains"
 246    var trackedDomains: [TrackedDomain] = DomainViewModel.loadTrackedDomains()
 247
 248    private static let historyKey = "lookupHistory"
 249    private static let maxHistory = 250
 250    var history: [HistoryEntry] = {
 251        guard let data = UserDefaults.standard.data(forKey: historyKey),
 252              let entries = try? JSONDecoder().decode([HistoryEntry].self, from: data) else {
 253            return []
 254        }
 255        return entries
 256    }()
 257    var historySearchText = ""
 258    var historyDateFilter: HistoryDateFilter = .all
 259    var historyChangeFilter: ChangeFilterOption = .all
 260    var historySortOption: HistorySortOption = .newest
 261    var watchlistSearchText = ""
 262    var watchlistFilter: WatchlistFilterOption = .all
 263    var watchlistSortOption: WatchlistSortOption = .pinned
 264
 265    var trimmedDomain: String {
 266        domain
 267            .trimmingCharacters(in: .whitespacesAndNewlines)
 268            .replacingOccurrences(of: "https://", with: "")
 269            .replacingOccurrences(of: "http://", with: "")
 270            .components(separatedBy: "/").first ?? ""
 271    }
 272
 273    var resultsLoaded: Bool {
 274        hasRun &&
 275            !dnsLoading &&
 276            !availabilityLoading &&
 277            !suggestionsLoading &&
 278            !sslLoading &&
 279            !hstsLoading &&
 280            !httpHeadersLoading &&
 281            !reachabilityLoading &&
 282            !ipGeolocationLoading &&
 283            !emailSecurityLoading &&
 284            !ptrLoading &&
 285            !redirectChainLoading &&
 286            !portScanLoading &&
 287            !customPortScanLoading
 288    }
 289
 290    var isCloudflareProxied: Bool {
 291        httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
 292    }
 293
 294    var isCurrentDomainSaved: Bool {
 295        !searchedDomain.isEmpty && savedDomains.contains(where: { $0.lowercased() == searchedDomain.lowercased() })
 296    }
 297
 298    var sortedTrackedDomains: [TrackedDomain] {
 299        sortedTrackedDomains(from: trackedDomains, using: .pinned)
 300    }
 301
 302    var filteredHistory: [HistoryEntry] {
 303        let calendar = Calendar.current
 304        let now = Date()
 305        let query = historySearchText.trimmingCharacters(in: .whitespacesAndNewlines)
 306
 307        return history
 308            .lazy
 309            .filter { entry in
 310                query.isEmpty || entry.domain.localizedCaseInsensitiveContains(query)
 311            }
 312            .filter { entry in
 313                switch self.historyDateFilter {
 314                case .today:
 315                    return calendar.isDate(entry.timestamp, inSameDayAs: now)
 316                case .last7Days:
 317                    guard let startDate = calendar.date(byAdding: .day, value: -7, to: now) else { return true }
 318                    return entry.timestamp >= startDate
 319                case .all:
 320                    return true
 321                }
 322            }
 323            .filter { entry in
 324                switch self.historyChangeFilter {
 325                case .all:
 326                    return true
 327                case .changed:
 328                    return entry.changeSummary?.hasChanges == true
 329                case .unchanged:
 330                    return entry.changeSummary?.hasChanges != true
 331                }
 332            }
 333            .sorted(by: historySortPredicate)
 334    }
 335
 336    var filteredTrackedDomains: [TrackedDomain] {
 337        let query = watchlistSearchText.trimmingCharacters(in: .whitespacesAndNewlines)
 338        let filtered = trackedDomains.filter { trackedDomain in
 339            if !query.isEmpty, !trackedDomain.domain.localizedCaseInsensitiveContains(query) {
 340                return false
 341            }
 342
 343            switch watchlistFilter {
 344            case .all:
 345                return true
 346            case .pinnedOnly:
 347                return trackedDomain.isPinned
 348            case .changedOnly:
 349                return trackedDomain.lastChangeSummary?.hasChanges == true
 350            }
 351        }
 352
 353        return sortedTrackedDomains(from: filtered, using: watchlistSortOption)
 354    }
 355
 356    var batchProgressLabel: String {
 357        guard batchTotalCount > 0 else { return "No active batch" }
 358        let domainLabel = batchCurrentDomain ?? "Preparing"
 359        return "\(batchCompletedCount + (batchLookupRunning ? 1 : 0))/\(batchTotalCount) • \(domainLabel)"
 360    }
 361
 362    var currentBatchResultEntries: [HistoryEntry] {
 363        batchResults.compactMap { result in
 364            guard let historyEntryID = result.historyEntryID else { return nil }
 365            return history.first(where: { $0.id == historyEntryID })
 366        }
 367    }
 368
 369    var currentTrackedDomain: TrackedDomain? {
 370        guard !searchedDomain.isEmpty else { return nil }
 371        return trackedDomain(for: searchedDomain)
 372    }
 373
 374    var isCurrentDomainTracked: Bool {
 375        currentTrackedDomain != nil
 376    }
 377
 378    var trackingLimitMessage: String? {
 379        nil
 380    }
 381
 382    var canTrackCurrentDomain: Bool {
 383        true
 384    }
 385
 386    var resolverDisplayName: String {
 387        DNSLookupService.currentResolverDisplayName()
 388    }
 389
 390    var resolverURLString: String {
 391        DNSLookupService.currentResolverURLString()
 392    }
 393
 394    var allPortScanResults: [PortScanResult] {
 395        (portScanResults + customPortResults).sorted {
 396            if $0.kind == $1.kind {
 397                return $0.port < $1.port
 398            }
 399            return $0.kind == .standard
 400        }
 401    }
 402
 403    var currentSnapshot: LookupSnapshot {
 404        LookupSnapshot(
 405            historyEntryID: nil,
 406            domain: searchedDomain,
 407            timestamp: Date(),
 408            trackedDomainID: currentTrackedDomain?.id,
 409            resolverDisplayName: resolverDisplayName,
 410            resolverURLString: resolverURLString,
 411            totalLookupDurationMs: lastLookupDurationMs,
 412            dnsSections: dnsSections,
 413            dnsError: dnsError,
 414            availabilityResult: availabilityResult,
 415            suggestions: suggestions,
 416            sslInfo: sslInfo,
 417            sslError: sslError,
 418            hstsPreloaded: hstsPreloaded,
 419            httpHeaders: httpHeaders,
 420            httpSecurityGrade: httpSecurityGrade,
 421            httpStatusCode: httpStatusCode,
 422            httpResponseTimeMs: httpResponseTimeMs,
 423            httpProtocol: httpProtocol,
 424            http3Advertised: http3Advertised,
 425            httpHeadersError: httpHeadersError,
 426            reachabilityResults: reachabilityResults,
 427            reachabilityError: reachabilityError,
 428            ipGeolocation: ipGeolocation,
 429            ipGeolocationError: ipGeolocationError,
 430            emailSecurity: emailSecurity,
 431            emailSecurityError: emailSecurityError,
 432            ptrRecord: ptrRecord,
 433            ptrError: ptrError,
 434            redirectChain: redirectChain,
 435            redirectChainError: redirectChainError,
 436            portScanResults: allPortScanResults,
 437            portScanError: combinedPortScanError,
 438            changeSummary: currentChangeSummary,
 439            isLive: true
 440        )
 441    }
 442
 443    var summaryFields: [SummaryFieldViewData] {
 444        Self.summaryFields(from: currentSnapshot)
 445    }
 446
 447    var domainRows: [InfoRowViewData] {
 448        Self.domainRows(from: currentSnapshot)
 449    }
 450
 451    var dnsRows: [DNSRecordSectionViewData] {
 452        Self.dnsRows(from: currentSnapshot)
 453    }
 454
 455    var suggestionRows: [DomainSuggestionViewData] {
 456        Self.suggestionRows(from: currentSnapshot)
 457    }
 458
 459    var dnssecLabel: String? {
 460        Self.dnssecLabel(from: currentSnapshot)
 461    }
 462
 463    var ptrMessage: SectionMessageViewData? {
 464        Self.ptrMessage(from: currentSnapshot)
 465    }
 466
 467    var webCertificateRows: [InfoRowViewData] {
 468        Self.webCertificateRows(from: currentSnapshot)
 469    }
 470
 471    var webResponseRows: [InfoRowViewData] {
 472        Self.webResponseRows(from: currentSnapshot)
 473    }
 474
 475    var redirectRows: [RedirectHopViewData] {
 476        Self.redirectRows(from: currentSnapshot)
 477    }
 478
 479    var emailRows: [EmailRowViewData] {
 480        Self.emailRows(from: currentSnapshot)
 481    }
 482
 483    var reachabilityRows: [ReachabilityRowViewData] {
 484        Self.reachabilityRows(from: currentSnapshot)
 485    }
 486
 487    var locationRows: [InfoRowViewData] {
 488        Self.locationRows(from: currentSnapshot)
 489    }
 490
 491    var standardPortRows: [PortScanRowViewData] {
 492        Self.portRows(from: currentSnapshot, kind: .standard)
 493    }
 494
 495    var customPortRows: [PortScanRowViewData] {
 496        Self.portRows(from: currentSnapshot, kind: .custom)
 497    }
 498
 499    var combinedPortScanError: String? {
 500        [portScanError, customPortScanError].compactMap { $0 }.joined(separator: "\n").nilIfEmpty
 501    }
 502
 503    func toggleSavedDomain() {
 504        if isCurrentDomainSaved {
 505            savedDomains.removeAll { $0.lowercased() == searchedDomain.lowercased() }
 506        } else {
 507            savedDomains.append(searchedDomain)
 508        }
 509        UserDefaults.standard.set(savedDomains, forKey: Self.savedDomainsKey)
 510    }
 511
 512    func removeSavedDomains(at offsets: IndexSet) {
 513        savedDomains.remove(atOffsets: offsets)
 514        UserDefaults.standard.set(savedDomains, forKey: Self.savedDomainsKey)
 515    }
 516
 517    @discardableResult
 518    func trackCurrentDomain() -> Bool {
 519        guard !searchedDomain.isEmpty else { return false }
 520        return trackDomain(domain: searchedDomain, availabilityStatus: availabilityResult?.status)
 521    }
 522
 523    @discardableResult
 524    func trackDomain(domain: String, availabilityStatus: DomainAvailabilityStatus?) -> Bool {
 525        let normalizedDomain = normalizedDomain(domain)
 526        guard !normalizedDomain.isEmpty else { return false }
 527
 528        if trackedDomain(for: normalizedDomain) != nil {
 529            return true
 530        }
 531
 532        guard PremiumAccessService.canAddTrackedDomain(currentCount: trackedDomains.count) else {
 533            return false
 534        }
 535
 536        trackedDomains.insert(
 537            TrackedDomain(
 538                domain: normalizedDomain,
 539                createdAt: Date(),
 540                updatedAt: Date(),
 541                lastKnownAvailability: availabilityStatus
 542            ),
 543            at: 0
 544        )
 545        persistTrackedDomains()
 546        linkTrackedDomainHistory(for: normalizedDomain)
 547        return true
 548    }
 549
 550    func refreshTrackedDomain(_ trackedDomain: TrackedDomain) {
 551        refreshingTrackedDomainID = trackedDomain.id
 552        domain = trackedDomain.domain
 553        run()
 554    }
 555
 556    func rerunInspection(for trackedDomain: TrackedDomain) {
 557        domain = trackedDomain.domain
 558        run()
 559        rerunNavigationToken = UUID()
 560    }
 561
 562    func deleteTrackedDomains(at offsets: IndexSet) {
 563        let ids = offsets.map { sortedTrackedDomains[$0].id }
 564        trackedDomains.removeAll { ids.contains($0.id) }
 565        history.indices.forEach { index in
 566            if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) {
 567                history[index].trackedDomainID = nil
 568            }
 569        }
 570        persistTrackedDomains()
 571        persistHistory()
 572    }
 573
 574    func deleteTrackedDomain(_ trackedDomain: TrackedDomain) {
 575        trackedDomains.removeAll { $0.id == trackedDomain.id }
 576        history.indices.forEach { index in
 577            if history[index].trackedDomainID == trackedDomain.id {
 578                history[index].trackedDomainID = nil
 579            }
 580        }
 581        persistTrackedDomains()
 582        persistHistory()
 583    }
 584
 585    func togglePinned(for trackedDomain: TrackedDomain) {
 586        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 587        trackedDomains[index].isPinned.toggle()
 588        persistTrackedDomains()
 589    }
 590
 591    func updateNote(_ note: String, for trackedDomain: TrackedDomain) {
 592        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 593        trackedDomains[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
 594        persistTrackedDomains()
 595    }
 596
 597    func removeHistoryEntries(at offsets: IndexSet) {
 598        history.remove(atOffsets: offsets)
 599        persistHistory()
 600    }
 601
 602    func removeHistoryEntries(withIDs ids: [UUID]) {
 603        history.removeAll { ids.contains($0.id) }
 604        persistHistory()
 605    }
 606
 607    func clearHistory() {
 608        history.removeAll()
 609        persistHistory()
 610    }
 611
 612    func clearRecentSearches() {
 613        recentSearches.removeAll()
 614        UserDefaults.standard.removeObject(forKey: Self.recentSearchesKey)
 615    }
 616
 617    func rerunLookup(from entry: HistoryEntry) {
 618        UserDefaults.standard.set(entry.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
 619        domain = entry.domain
 620        run()
 621        rerunNavigationToken = UUID()
 622    }
 623
 624    func reset() {
 625        lookupTask?.cancel()
 626        customPortScanTask?.cancel()
 627        hasRun = false
 628        searchedDomain = ""
 629        lastLookupDurationMs = nil
 630        currentDiffSections = []
 631        currentChangeSummary = nil
 632        refreshingTrackedDomainID = nil
 633        clearBatchState()
 634        clearLookupState()
 635    }
 636
 637    func run() {
 638        let target = trimmedDomain
 639        guard !target.isEmpty else { return }
 640        clearBatchState()
 641        let lookupID = beginLookup(for: target)
 642
 643        lookupTask = Task { [weak self] in
 644            guard let self else { return }
 645            _ = await self.performLookup(domain: target, lookupID: lookupID)
 646        }
 647    }
 648
 649    func runBulkLookup() {
 650        let domains = parsedDomains(from: bulkInput)
 651        guard !domains.isEmpty else { return }
 652
 653        clearBatchState()
 654        batchLookupSource = .manual
 655        batchTotalCount = domains.count
 656        batchLookupRunning = true
 657        batchResults = domains.map {
 658            BatchLookupResult(
 659                domain: $0,
 660                historyEntryID: nil,
 661                availability: nil,
 662                primaryIP: nil,
 663                quickStatus: "Pending",
 664                timestamp: Date(),
 665                status: .pending
 666            )
 667        }
 668
 669        lookupTask?.cancel()
 670        customPortScanTask?.cancel()
 671
 672        lookupTask = Task { [weak self] in
 673            guard let self else { return }
 674            await self.runBatchLookup(domains: domains, source: .manual)
 675        }
 676    }
 677
 678    func refreshAllTrackedDomains() {
 679        let domains = sortedTrackedDomains.map(\.domain)
 680        guard !domains.isEmpty else { return }
 681
 682        clearBatchState()
 683        batchLookupSource = .watchlistRefresh
 684        batchTotalCount = domains.count
 685        batchLookupRunning = true
 686        batchResults = domains.map {
 687            BatchLookupResult(
 688                domain: $0,
 689                historyEntryID: nil,
 690                availability: nil,
 691                primaryIP: nil,
 692                quickStatus: "Pending",
 693                timestamp: Date(),
 694                status: .pending
 695            )
 696        }
 697
 698        lookupTask?.cancel()
 699        customPortScanTask?.cancel()
 700
 701        lookupTask = Task { [weak self] in
 702            guard let self else { return }
 703            await self.runBatchLookup(domains: domains, source: .watchlistRefresh)
 704        }
 705    }
 706
 707    func runCustomPortScan(ports: [UInt16]) async {
 708        guard !searchedDomain.isEmpty else {
 709            customPortScanError = "Run a domain lookup first"
 710            return
 711        }
 712
 713        guard !ports.isEmpty else {
 714            customPortScanError = "Enter at least one valid port"
 715            customPortResults = []
 716            return
 717        }
 718
 719        customPortScanTask?.cancel()
 720        let domain = searchedDomain
 721        let lookupID = activeLookupID
 722
 723        customPortScanLoading = true
 724        customPortScanError = nil
 725        customPortResults = []
 726
 727        customPortScanTask = Task { [weak self] in
 728            guard let self else { return }
 729            let result = await PortScanService.scanPorts(domain: domain, ports: ports, timeout: 3.0)
 730            guard !Task.isCancelled, self.isCurrentLookup(lookupID) else { return }
 731            self.applyCustomPortResult(result)
 732        }
 733    }
 734
 735    func exportText() -> String {
 736        Self.formatExportText(
 737            from: currentSnapshot,
 738            trackedDomain: currentTrackedDomain,
 739            changeSummary: currentChangeSummary,
 740            diffSections: currentDiffSections
 741        )
 742    }
 743
 744    func exportCSV() -> String {
 745        Self.formatCSV(from: [currentSnapshot])
 746    }
 747
 748    func exportBatchText() -> String {
 749        Self.formatBatchExportText(
 750            title: batchLookupSource == .watchlistRefresh ? "Tracked Domains Export" : "Batch Results Export",
 751            entries: currentBatchResultEntries.map { entry in
 752                (
 753                    snapshot: entry.snapshot,
 754                    trackedDomain: trackedDomains.first(where: { tracked in
 755                        tracked.id == entry.trackedDomainID ||
 756                        tracked.domain.caseInsensitiveCompare(entry.domain) == .orderedSame
 757                    }),
 758                    changeSummary: entry.changeSummary,
 759                    diffSections: comparisonSnapshot(for: entry).map { DomainDiffService.diff(from: $0, to: entry.snapshot) } ?? []
 760                )
 761            }
 762        )
 763    }
 764
 765    func exportBatchCSV() -> String {
 766        Self.formatCSV(from: currentBatchResultEntries.map(\.snapshot))
 767    }
 768
 769    func exportTrackedDomainsCSV(domains: [TrackedDomain]) -> String {
 770        Self.formatCSV(from: exportSnapshots(for: domains))
 771    }
 772
 773    func exportTrackedDomainsText(domains: [TrackedDomain]) -> String {
 774        let latestEntries = latestSnapshots(for: domains)
 775        return Self.formatBatchExportText(
 776            title: "Tracked Domains Export",
 777            entries: domains.map { trackedDomain in
 778                if let entry = latestEntries.first(where: { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }) {
 779                    return (
 780                        snapshot: entry.snapshot,
 781                        trackedDomain: trackedDomain,
 782                        changeSummary: entry.changeSummary,
 783                        diffSections: comparisonSnapshot(for: entry).map { DomainDiffService.diff(from: $0, to: entry.snapshot) } ?? []
 784                    )
 785                }
 786
 787                return (
 788                    snapshot: placeholderSnapshot(for: trackedDomain),
 789                    trackedDomain: trackedDomain,
 790                    changeSummary: trackedDomain.lastChangeSummary,
 791                    diffSections: []
 792                )
 793            }
 794        )
 795    }
 796
 797    private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? {
 798        await withTaskGroup(of: Void.self) { group in
 799            group.addTask { await self.runDNS(domain: domain, lookupID: lookupID) }
 800            group.addTask { await self.runAvailability(domain: domain, lookupID: lookupID) }
 801            group.addTask { await self.runSSL(domain: domain, lookupID: lookupID) }
 802            group.addTask { await self.runHSTSPreload(domain: domain, lookupID: lookupID) }
 803        }
 804
 805        await withTaskGroup(of: Void.self) { group in
 806            group.addTask { await self.runHTTPHeaders(domain: domain, lookupID: lookupID) }
 807            group.addTask { await self.runReachability(domain: domain, lookupID: lookupID) }
 808            group.addTask { await self.runRedirectChain(domain: domain, lookupID: lookupID) }
 809            group.addTask { await self.runPortScan(domain: domain, lookupID: lookupID) }
 810        }
 811
 812        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
 813
 814        let txtRecords = dnsSections.first(where: { $0.recordType == .TXT })?.records ?? []
 815        let primaryIP = primaryIPAddress(from: dnsSections)
 816
 817        await withTaskGroup(of: Void.self) { group in
 818            group.addTask { await self.runEmailSecurity(domain: domain, txtRecords: txtRecords, lookupID: lookupID) }
 819            if let primaryIP {
 820                group.addTask { await self.runReverseDNS(ip: primaryIP, lookupID: lookupID) }
 821                group.addTask { await self.runIPGeolocation(ip: primaryIP, lookupID: lookupID) }
 822            } else {
 823                group.addTask { await self.finishDependentWithoutPrimaryIP(lookupID: lookupID) }
 824            }
 825        }
 826
 827        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
 828
 829        if availabilityResult?.status == .registered {
 830            await runSuggestions(domain: domain, lookupID: lookupID)
 831        } else {
 832            suggestions = []
 833            suggestionsLoading = false
 834        }
 835
 836        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
 837        lastLookupDurationMs = lookupStartedAt.map { Int(Date().timeIntervalSince($0) * 1000) }
 838        let entry = saveHistoryEntry(replaceLatest: false)
 839        refreshingTrackedDomainID = nil
 840        return entry
 841    }
 842
 843    private func runDNS(domain: String, lookupID: UUID) async {
 844        let result = await DNSLookupService.lookupAll(domain: domain)
 845        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 846        switch result {
 847        case let .success(sections):
 848            dnsSections = sections
 849            dnsError = nil
 850        case let .empty(message):
 851            dnsSections = []
 852            dnsError = message
 853        case let .error(message):
 854            dnsSections = []
 855            dnsError = message
 856        }
 857        dnsLoading = false
 858    }
 859
 860    private func runAvailability(domain: String, lookupID: UUID) async {
 861        let result = await DomainAvailabilityService.check(domain: domain)
 862        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 863        availabilityResult = result
 864        availabilityLoading = false
 865        updateTrackedDomainAvailability(for: result.domain, status: result.status)
 866    }
 867
 868    private func runSSL(domain: String, lookupID: UUID) async {
 869        let result = await SSLCheckService.check(domain: domain)
 870        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 871        switch result {
 872        case let .success(info):
 873            sslInfo = info
 874            sslError = nil
 875        case let .empty(message):
 876            sslInfo = nil
 877            sslError = message
 878        case let .error(message):
 879            sslInfo = nil
 880            sslError = message
 881        }
 882        sslLoading = false
 883    }
 884
 885    private func runHSTSPreload(domain: String, lookupID: UUID) async {
 886        let result = await SSLCheckService.checkHSTSPreload(domain: domain)
 887        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 888        hstsPreloaded = result
 889        hstsLoading = false
 890    }
 891
 892    private func runHTTPHeaders(domain: String, lookupID: UUID) async {
 893        let result = await HTTPHeadersService.fetch(domain: domain)
 894        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 895        switch result {
 896        case let .success(headersResult):
 897            httpHeaders = headersResult.headers
 898            httpSecurityGrade = HTTPSecurityGrade.grade(for: headersResult.headers).rawValue
 899            httpStatusCode = headersResult.statusCode
 900            httpResponseTimeMs = headersResult.responseTimeMs
 901            httpProtocol = headersResult.httpProtocol
 902            http3Advertised = headersResult.http3Advertised
 903            httpHeadersError = nil
 904        case let .empty(message):
 905            httpHeaders = []
 906            httpSecurityGrade = nil
 907            httpStatusCode = nil
 908            httpResponseTimeMs = nil
 909            httpProtocol = nil
 910            http3Advertised = false
 911            httpHeadersError = message
 912        case let .error(message):
 913            httpHeaders = []
 914            httpSecurityGrade = nil
 915            httpStatusCode = nil
 916            httpResponseTimeMs = nil
 917            httpProtocol = nil
 918            http3Advertised = false
 919            httpHeadersError = message
 920        }
 921        httpHeadersLoading = false
 922    }
 923
 924    private func runReachability(domain: String, lookupID: UUID) async {
 925        let result = await ReachabilityService.checkAll(domain: domain)
 926        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 927        switch result {
 928        case let .success(results):
 929            reachabilityResults = results
 930            reachabilityError = nil
 931        case let .empty(message):
 932            reachabilityResults = []
 933            reachabilityError = message
 934        case let .error(message):
 935            reachabilityResults = []
 936            reachabilityError = message
 937        }
 938        reachabilityLoading = false
 939    }
 940
 941    private func runEmailSecurity(domain: String, txtRecords: [DNSRecord], lookupID: UUID) async {
 942        let result = await EmailSecurityService.analyze(domain: domain, txtRecords: txtRecords)
 943        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 944        switch result {
 945        case let .success(emailResult):
 946            emailSecurity = emailResult
 947            emailSecurityError = nil
 948        case let .empty(message):
 949            emailSecurity = nil
 950            emailSecurityError = message
 951        case let .error(message):
 952            emailSecurity = nil
 953            emailSecurityError = message
 954        }
 955        emailSecurityLoading = false
 956    }
 957
 958    private func runReverseDNS(ip: String, lookupID: UUID) async {
 959        let result = await ReverseDNSService.lookup(ip: ip, resolverURLString: resolverURLString)
 960        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 961        switch result {
 962        case let .success(record):
 963            ptrRecord = record
 964            ptrError = nil
 965        case let .empty(message):
 966            ptrRecord = nil
 967            ptrError = message
 968        case let .error(message):
 969            ptrRecord = nil
 970            ptrError = message
 971        }
 972        ptrLoading = false
 973    }
 974
 975    private func runRedirectChain(domain: String, lookupID: UUID) async {
 976        let result = await RedirectChainService.trace(domain: domain)
 977        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 978        switch result {
 979        case let .success(hops):
 980            redirectChain = hops
 981            redirectChainError = nil
 982        case let .empty(message):
 983            redirectChain = []
 984            redirectChainError = message
 985        case let .error(message):
 986            redirectChain = []
 987            redirectChainError = message
 988        }
 989        redirectChainLoading = false
 990    }
 991
 992    private func runPortScan(domain: String, lookupID: UUID) async {
 993        let result = await PortScanService.scanAll(domain: domain)
 994        switch result {
 995        case let .success(results):
 996            let enrichedResults = await enrichOpenPortBanners(in: results, domain: domain)
 997            guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
 998            portScanResults = enrichedResults
 999            portScanError = nil
1000        case let .empty(message):
1001            guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1002            portScanResults = []
1003            portScanError = message
1004        case let .error(message):
1005            guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1006            portScanResults = []
1007            portScanError = message
1008        }
1009        portScanLoading = false
1010    }
1011
1012    private func runIPGeolocation(ip: String, lookupID: UUID) async {
1013        let result = await IPGeolocationService.lookup(ip: ip)
1014        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1015        switch result {
1016        case let .success(geolocation):
1017            ipGeolocation = geolocation
1018            ipGeolocationError = nil
1019        case let .empty(message):
1020            ipGeolocation = nil
1021            ipGeolocationError = message
1022        case let .error(message):
1023            ipGeolocation = nil
1024            ipGeolocationError = message
1025        }
1026        ipGeolocationLoading = false
1027    }
1028
1029    private func finishDependentWithoutPrimaryIP(lookupID: UUID) async {
1030        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1031        ptrLoading = false
1032        ptrError = "No A record available"
1033        ipGeolocationLoading = false
1034        ipGeolocationError = "No A record available"
1035    }
1036
1037    private func runSuggestions(domain: String, lookupID: UUID) async {
1038        let results = await DomainAvailabilityService.suggestions(for: domain)
1039        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return }
1040        suggestions = results
1041        suggestionsLoading = false
1042    }
1043
1044    private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) {
1045        switch result {
1046        case let .success(results):
1047            customPortResults = results
1048            customPortScanError = nil
1049            _ = saveHistoryEntry(replaceLatest: true)
1050        case let .empty(message):
1051            customPortResults = []
1052            customPortScanError = message
1053        case let .error(message):
1054            customPortResults = []
1055            customPortScanError = message
1056        }
1057        customPortScanLoading = false
1058    }
1059
1060    private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
1061        let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
1062            for result in results where result.open {
1063                group.addTask {
1064                    let banner = await PortScanService.grabBanner(host: domain, port: result.port)
1065                    return (result.port, banner)
1066                }
1067            }
1068
1069            var collected: [UInt16: String] = [:]
1070            for await (port, banner) in group {
1071                if let banner {
1072                    collected[port] = banner
1073                }
1074            }
1075            return collected
1076        }
1077
1078        return results.map { result in
1079            var updated = result
1080            updated.banner = banners[result.port]
1081            return updated
1082        }
1083    }
1084
1085    @discardableResult
1086    private func saveHistoryEntry(replaceLatest: Bool) -> HistoryEntry? {
1087        guard !searchedDomain.isEmpty else { return nil }
1088
1089        let trackedDomainID = trackedDomain(for: searchedDomain)?.id
1090        let timestamp = Date()
1091        let snapshot = currentSnapshot
1092        let previousSnapshot = previousSnapshot(for: searchedDomain, trackedDomainID: trackedDomainID, replacingLatest: replaceLatest)
1093        let changeSummary = previousSnapshot.map { DomainDiffService.summary(from: $0, to: snapshot, generatedAt: timestamp) }
1094
1095        currentChangeSummary = changeSummary
1096        currentDiffSections = previousSnapshot.map { DomainDiffService.diff(from: $0, to: snapshot) } ?? []
1097
1098        let entry = HistoryEntry(
1099            domain: searchedDomain,
1100            timestamp: timestamp,
1101            trackedDomainID: trackedDomainID,
1102            dnsSections: dnsSections,
1103            sslInfo: sslInfo,
1104            httpHeaders: httpHeaders,
1105            reachabilityResults: reachabilityResults,
1106            ipGeolocation: ipGeolocation,
1107            emailSecurity: emailSecurity,
1108            mtaSts: emailSecurity?.mtaSts,
1109            ptrRecord: ptrRecord,
1110            redirectChain: redirectChain,
1111            portScanResults: allPortScanResults,
1112            hstsPreloaded: hstsPreloaded,
1113            availabilityResult: availabilityResult,
1114            suggestions: suggestions,
1115            resolverDisplayName: resolverDisplayName,
1116            resolverURLString: resolverURLString,
1117            totalLookupDurationMs: lastLookupDurationMs,
1118            primaryIP: Self.primaryIPAddress(from: snapshot),
1119            finalRedirectURL: Self.finalRedirectTarget(from: snapshot),
1120            tlsStatusSummary: Self.httpsSummary(from: snapshot),
1121            emailSecuritySummary: Self.emailSummary(from: snapshot),
1122            httpGradeSummary: snapshot.httpSecurityGrade ?? snapshot.httpHeadersError,
1123            changeSummary: changeSummary,
1124            sslError: sslError,
1125            httpHeadersError: httpHeadersError,
1126            reachabilityError: reachabilityError,
1127            ipGeolocationError: ipGeolocationError,
1128            emailSecurityError: emailSecurityError,
1129            ptrError: ptrError,
1130            redirectChainError: redirectChainError,
1131            portScanError: combinedPortScanError
1132        )
1133
1134        if replaceLatest, !history.isEmpty, history[0].domain.caseInsensitiveCompare(searchedDomain) == .orderedSame {
1135            history[0] = entry
1136        } else {
1137            history.insert(entry, at: 0)
1138            if history.count > Self.maxHistory {
1139                history = Array(history.prefix(Self.maxHistory))
1140            }
1141        }
1142
1143        updateTrackedDomainSnapshotMetadata(
1144            domain: searchedDomain,
1145            snapshotID: entry.id,
1146            availabilityStatus: availabilityResult?.status,
1147            updatedAt: timestamp,
1148            changeSummary: changeSummary
1149        )
1150        persistHistory()
1151        return entry
1152    }
1153
1154    private func persistHistory() {
1155        if let data = try? JSONEncoder().encode(history) {
1156            UserDefaults.standard.set(data, forKey: Self.historyKey)
1157        }
1158    }
1159
1160    private func persistTrackedDomains() {
1161        if let data = try? JSONEncoder().encode(trackedDomains) {
1162            UserDefaults.standard.set(data, forKey: Self.trackedDomainsKey)
1163        }
1164    }
1165
1166    private func updateTrackedDomainAvailability(for domain: String, status: DomainAvailabilityStatus) {
1167        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1168            return
1169        }
1170        trackedDomains[index].lastKnownAvailability = status
1171        persistTrackedDomains()
1172    }
1173
1174    private func updateTrackedDomainSnapshotMetadata(
1175        domain: String,
1176        snapshotID: UUID,
1177        availabilityStatus: DomainAvailabilityStatus?,
1178        updatedAt: Date,
1179        changeSummary: DomainChangeSummary?
1180    ) {
1181        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1182            return
1183        }
1184        trackedDomains[index].lastSnapshotID = snapshotID
1185        trackedDomains[index].lastKnownAvailability = availabilityStatus
1186        trackedDomains[index].updatedAt = updatedAt
1187        trackedDomains[index].lastChangeSummary = changeSummary
1188        persistTrackedDomains()
1189    }
1190
1191    private func previousSnapshot(for domain: String, trackedDomainID: UUID?, replacingLatest: Bool) -> LookupSnapshot? {
1192        let matchingEntries = history.filter { entry in
1193            if let trackedDomainID {
1194                return entry.trackedDomainID == trackedDomainID
1195            }
1196            return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1197        }
1198
1199        if replacingLatest {
1200            return matchingEntries.dropFirst().first?.snapshot
1201        }
1202        return matchingEntries.first?.snapshot
1203    }
1204
1205    private func trackedDomain(for domain: String) -> TrackedDomain? {
1206        trackedDomains.first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }
1207    }
1208
1209    private func normalizedDomain(_ domain: String) -> String {
1210        domain
1211            .trimmingCharacters(in: .whitespacesAndNewlines)
1212            .replacingOccurrences(of: "https://", with: "")
1213            .replacingOccurrences(of: "http://", with: "")
1214            .components(separatedBy: "/")
1215            .first?
1216            .lowercased() ?? ""
1217    }
1218
1219    private func linkTrackedDomainHistory(for domain: String) {
1220        guard let trackedDomain = trackedDomain(for: domain) else { return }
1221        var didChange = false
1222
1223        for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
1224            if history[index].trackedDomainID != trackedDomain.id {
1225                history[index].trackedDomainID = trackedDomain.id
1226                didChange = true
1227            }
1228        }
1229
1230        if didChange {
1231            persistHistory()
1232        }
1233
1234        if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
1235           let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
1236            trackedDomains[trackedIndex].lastSnapshotID = latestEntry.id
1237            trackedDomains[trackedIndex].lastChangeSummary = latestEntry.changeSummary
1238            trackedDomains[trackedIndex].lastKnownAvailability = latestEntry.availabilityResult?.status
1239            trackedDomains[trackedIndex].updatedAt = latestEntry.timestamp
1240            persistTrackedDomains()
1241        }
1242    }
1243
1244    private func addRecentSearch(_ domain: String) {
1245        recentSearches.removeAll { $0.lowercased() == domain.lowercased() }
1246        recentSearches.insert(domain, at: 0)
1247        if recentSearches.count > Self.maxRecent {
1248            recentSearches = Array(recentSearches.prefix(Self.maxRecent))
1249        }
1250        UserDefaults.standard.set(recentSearches, forKey: Self.recentSearchesKey)
1251    }
1252
1253    private func beginLookup(for target: String, cancelExistingTask: Bool = true) -> UUID {
1254        if cancelExistingTask {
1255            lookupTask?.cancel()
1256        }
1257        customPortScanTask?.cancel()
1258
1259        let lookupID = UUID()
1260        activeLookupID = lookupID
1261        lookupStartedAt = Date()
1262        lastLookupDurationMs = nil
1263        addRecentSearch(target)
1264        searchedDomain = target
1265        hasRun = true
1266        currentDiffSections = []
1267        currentChangeSummary = nil
1268        clearLookupState()
1269        setAllLoadingStates(true)
1270        customPortScanLoading = false
1271        return lookupID
1272    }
1273
1274    private func clearBatchState() {
1275        batchResults = []
1276        batchLookupSource = .manual
1277        batchCurrentDomain = nil
1278        batchCompletedCount = 0
1279        batchTotalCount = 0
1280        batchLookupRunning = false
1281    }
1282
1283    private func parsedDomains(from input: String) -> [String] {
1284        let separators = CharacterSet(charactersIn: ",\n")
1285        var seen = Set<String>()
1286
1287        return input
1288            .components(separatedBy: separators)
1289            .map(normalizedDomain)
1290            .filter { !$0.isEmpty }
1291            .filter { seen.insert($0).inserted }
1292    }
1293
1294    private func runBatchLookup(domains: [String], source: BatchLookupSource) async {
1295        for (index, domain) in domains.enumerated() {
1296            guard !Task.isCancelled else { break }
1297
1298            batchCurrentDomain = domain
1299            if source == .watchlistRefresh {
1300                refreshingTrackedDomainID = trackedDomain(for: domain)?.id
1301            }
1302            updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil)
1303
1304            let lookupID = beginLookup(for: domain, cancelExistingTask: false)
1305            let entry = await performLookup(domain: domain, lookupID: lookupID)
1306
1307            if let entry {
1308                updateBatchResult(
1309                    domain: domain,
1310                    status: .completed,
1311                    quickStatus: entry.changeSummary?.hasChanges == true ? "Changed" : "Unchanged",
1312                    entry: entry,
1313                    errorMessage: nil
1314                )
1315            } else {
1316                updateBatchResult(
1317                    domain: domain,
1318                    status: .failed,
1319                    quickStatus: "Failed",
1320                    entry: nil,
1321                    errorMessage: "Lookup cancelled"
1322                )
1323            }
1324
1325            batchCompletedCount = index + 1
1326        }
1327
1328        batchLookupRunning = false
1329        batchCurrentDomain = nil
1330        refreshingTrackedDomainID = nil
1331    }
1332
1333    private func updateBatchResult(
1334        domain: String,
1335        status: BatchLookupStatus,
1336        quickStatus: String,
1337        entry: HistoryEntry?,
1338        errorMessage: String?
1339    ) {
1340        guard let index = batchResults.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1341            return
1342        }
1343
1344        batchResults[index] = BatchLookupResult(
1345            id: batchResults[index].id,
1346            domain: domain,
1347            historyEntryID: entry?.id,
1348            availability: entry?.availabilityResult?.status,
1349            primaryIP: entry?.primaryIP,
1350            quickStatus: quickStatus,
1351            timestamp: entry?.timestamp ?? Date(),
1352            status: status,
1353            errorMessage: errorMessage
1354        )
1355    }
1356
1357    private func clearLookupState() {
1358        dnsSections = []
1359        dnsError = nil
1360        dnsLoading = false
1361        availabilityResult = nil
1362        availabilityLoading = false
1363        suggestions = []
1364        suggestionsLoading = false
1365        sslInfo = nil
1366        sslError = nil
1367        sslLoading = false
1368        hstsPreloaded = nil
1369        hstsLoading = false
1370        httpHeaders = []
1371        httpSecurityGrade = nil
1372        httpStatusCode = nil
1373        httpResponseTimeMs = nil
1374        httpProtocol = nil
1375        http3Advertised = false
1376        httpHeadersError = nil
1377        httpHeadersLoading = false
1378        reachabilityResults = []
1379        reachabilityError = nil
1380        reachabilityLoading = false
1381        ipGeolocation = nil
1382        ipGeolocationError = nil
1383        ipGeolocationLoading = false
1384        emailSecurity = nil
1385        emailSecurityError = nil
1386        emailSecurityLoading = false
1387        ptrRecord = nil
1388        ptrError = nil
1389        ptrLoading = false
1390        redirectChain = []
1391        redirectChainError = nil
1392        redirectChainLoading = false
1393        portScanResults = []
1394        portScanError = nil
1395        portScanLoading = false
1396        customPortResults = []
1397        customPortScanError = nil
1398        customPortScanLoading = false
1399    }
1400
1401    private func setAllLoadingStates(_ loading: Bool) {
1402        dnsLoading = loading
1403        availabilityLoading = loading
1404        suggestionsLoading = loading
1405        sslLoading = loading
1406        hstsLoading = loading
1407        httpHeadersLoading = loading
1408        reachabilityLoading = loading
1409        ipGeolocationLoading = loading
1410        emailSecurityLoading = loading
1411        ptrLoading = loading
1412        redirectChainLoading = loading
1413        portScanLoading = loading
1414    }
1415
1416    private func primaryIPAddress(from sections: [DNSSection]) -> String? {
1417        sections.first(where: { $0.recordType == .A })?.records.first?.value
1418    }
1419
1420    private func isCurrentLookup(_ lookupID: UUID) -> Bool {
1421        activeLookupID == lookupID
1422    }
1423
1424    func recentSnapshots(for trackedDomain: TrackedDomain, limit: Int = 6) -> [HistoryEntry] {
1425        history
1426            .filter { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
1427            .sorted { $0.timestamp > $1.timestamp }
1428            .prefix(limit)
1429            .map { $0 }
1430    }
1431
1432    func latestSnapshots(for domains: [TrackedDomain]) -> [HistoryEntry] {
1433        domains.compactMap { trackedDomain in
1434            recentSnapshots(for: trackedDomain, limit: 1).first
1435        }
1436    }
1437
1438    func diffSectionsForLatestSnapshots(of trackedDomain: TrackedDomain) -> [DomainDiffSection] {
1439        let snapshots = recentSnapshots(for: trackedDomain, limit: 2)
1440        guard snapshots.count == 2 else { return [] }
1441        return DomainDiffService.diff(from: snapshots[1].snapshot, to: snapshots[0].snapshot)
1442    }
1443
1444    func latestChangeSummary(for trackedDomain: TrackedDomain) -> DomainChangeSummary? {
1445        trackedDomain.lastChangeSummary ?? recentSnapshots(for: trackedDomain, limit: 1).first?.changeSummary
1446    }
1447
1448    func comparisonSnapshot(for entry: HistoryEntry) -> LookupSnapshot? {
1449        let siblings = history.filter { candidate in
1450            if let trackedDomainID = entry.trackedDomainID {
1451                return candidate.trackedDomainID == trackedDomainID && candidate.id != entry.id
1452            }
1453            return candidate.domain.caseInsensitiveCompare(entry.domain) == .orderedSame && candidate.id != entry.id
1454        }
1455        .sorted { $0.timestamp > $1.timestamp }
1456
1457        return siblings.first?.snapshot
1458    }
1459
1460    func historyEntry(for batchResult: BatchLookupResult) -> HistoryEntry? {
1461        guard let historyEntryID = batchResult.historyEntryID else { return nil }
1462        return history.first(where: { $0.id == historyEntryID })
1463    }
1464
1465    private func exportSnapshots(for domains: [TrackedDomain]) -> [LookupSnapshot] {
1466        let latestEntries = latestSnapshots(for: domains)
1467
1468        return domains.map { trackedDomain in
1469            if let entry = latestEntries.first(where: { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }) {
1470                return entry.snapshot
1471            }
1472            return placeholderSnapshot(for: trackedDomain)
1473        }
1474    }
1475
1476    private func placeholderSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot {
1477        LookupSnapshot(
1478            historyEntryID: trackedDomain.lastSnapshotID,
1479            domain: trackedDomain.domain,
1480            timestamp: trackedDomain.updatedAt,
1481            trackedDomainID: trackedDomain.id,
1482            resolverDisplayName: resolverDisplayName,
1483            resolverURLString: resolverURLString,
1484            totalLookupDurationMs: nil,
1485            dnsSections: [],
1486            dnsError: nil,
1487            availabilityResult: DomainAvailabilityResult(domain: trackedDomain.domain, status: trackedDomain.lastKnownAvailability ?? .unknown),
1488            suggestions: [],
1489            sslInfo: nil,
1490            sslError: nil,
1491            hstsPreloaded: nil,
1492            httpHeaders: [],
1493            httpSecurityGrade: nil,
1494            httpStatusCode: nil,
1495            httpResponseTimeMs: nil,
1496            httpProtocol: nil,
1497            http3Advertised: false,
1498            httpHeadersError: nil,
1499            reachabilityResults: [],
1500            reachabilityError: nil,
1501            ipGeolocation: nil,
1502            ipGeolocationError: nil,
1503            emailSecurity: nil,
1504            emailSecurityError: nil,
1505            ptrRecord: nil,
1506            ptrError: nil,
1507            redirectChain: [],
1508            redirectChainError: nil,
1509            portScanResults: [],
1510            portScanError: nil,
1511            changeSummary: trackedDomain.lastChangeSummary,
1512            isLive: false
1513        )
1514    }
1515
1516    private static func loadTrackedDomains() -> [TrackedDomain] {
1517        let defaults = UserDefaults.standard
1518        let decoder = JSONDecoder()
1519
1520        if let data = defaults.data(forKey: trackedDomainsKey),
1521           let domains = try? decoder.decode([TrackedDomain].self, from: data) {
1522            return deduplicatedTrackedDomains(domains)
1523        }
1524
1525        if let legacyData = defaults.data(forKey: legacyWatchedDomainsKey),
1526           let legacyDomains = try? decoder.decode([WatchedDomain].self, from: legacyData) {
1527            return deduplicatedTrackedDomains(
1528                legacyDomains.map {
1529                    TrackedDomain(
1530                        id: $0.id,
1531                        domain: $0.domain.lowercased(),
1532                        createdAt: $0.createdAt,
1533                        updatedAt: $0.createdAt,
1534                        lastKnownAvailability: $0.lastKnownAvailability
1535                    )
1536                }
1537            )
1538        }
1539
1540        return []
1541    }
1542
1543    private static func deduplicatedTrackedDomains(_ domains: [TrackedDomain]) -> [TrackedDomain] {
1544        var seen = Set<String>()
1545        return domains.filter { domain in
1546            let key = domain.domain.lowercased()
1547            return seen.insert(key).inserted
1548        }
1549    }
1550
1551    private func historySortPredicate(lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
1552        switch historySortOption {
1553        case .newest:
1554            return lhs.timestamp > rhs.timestamp
1555        case .oldest:
1556            return lhs.timestamp < rhs.timestamp
1557        case .domain:
1558            let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
1559            if domainOrder != .orderedSame {
1560                return domainOrder == .orderedAscending
1561            }
1562            return lhs.timestamp > rhs.timestamp
1563        }
1564    }
1565
1566    private func sortedTrackedDomains(from domains: [TrackedDomain], using sortOption: WatchlistSortOption) -> [TrackedDomain] {
1567        domains.sorted { lhs, rhs in
1568            switch sortOption {
1569            case .pinned:
1570                if lhs.isPinned != rhs.isPinned {
1571                    return lhs.isPinned && !rhs.isPinned
1572                }
1573                if lhs.updatedAt != rhs.updatedAt {
1574                    return lhs.updatedAt > rhs.updatedAt
1575                }
1576                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
1577            case .recentlyUpdated:
1578                if lhs.updatedAt != rhs.updatedAt {
1579                    return lhs.updatedAt > rhs.updatedAt
1580                }
1581                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
1582            case .alphabetical:
1583                let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
1584                if domainOrder != .orderedSame {
1585                    return domainOrder == .orderedAscending
1586                }
1587                return lhs.updatedAt > rhs.updatedAt
1588            }
1589        }
1590    }
1591
1592    static func summaryFields(from snapshot: LookupSnapshot) -> [SummaryFieldViewData] {
1593        [
1594            SummaryFieldViewData(label: "Domain", value: snapshot.domain.nonEmpty ?? "Unavailable", tone: .primary),
1595            SummaryFieldViewData(label: "Primary IP", value: primaryIPAddress(from: snapshot) ?? "Unavailable", tone: .primary),
1596            SummaryFieldViewData(label: "HTTPS", value: httpsSummary(from: snapshot), tone: httpsSummaryTone(from: snapshot)),
1597            SummaryFieldViewData(label: "Redirect", value: finalRedirectTarget(from: snapshot) ?? "Unavailable", tone: .secondary),
1598            SummaryFieldViewData(label: "Email", value: emailSummary(from: snapshot), tone: .secondary)
1599        ]
1600    }
1601
1602    static func domainRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1603        var rows = [
1604            InfoRowViewData(label: "Domain", value: snapshot.domain, tone: .primary),
1605            InfoRowViewData(label: "Resolver", value: snapshot.resolverDisplayName, tone: .secondary),
1606            InfoRowViewData(label: snapshot.isLive ? "Result" : "Snapshot", value: snapshot.isLive ? "Live" : "Snapshot", tone: snapshot.isLive ? .success : .warning),
1607            InfoRowViewData(label: "Lookup Duration", value: durationLabel(snapshot.totalLookupDurationMs), tone: .secondary)
1608        ]
1609        rows.insert(
1610            InfoRowViewData(
1611                label: "Availability",
1612                value: availabilityLabel(snapshot.availabilityResult?.status),
1613                tone: availabilityTone(snapshot.availabilityResult?.status)
1614            ),
1615            at: 1
1616        )
1617        return rows
1618    }
1619
1620    static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
1621        snapshot.suggestions.map {
1622            DomainSuggestionViewData(
1623                id: $0.id,
1624                domain: $0.domain,
1625                status: availabilityLabel($0.status),
1626                tone: availabilityTone($0.status)
1627            )
1628        }
1629    }
1630
1631    static func dnsRows(from snapshot: LookupSnapshot) -> [DNSRecordSectionViewData] {
1632        snapshot.dnsSections.map { section in
1633            DNSRecordSectionViewData(
1634                title: section.recordType.rawValue,
1635                rows: section.records.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary) },
1636                wildcardRows: section.wildcardRecords.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary) },
1637                wildcardTitle: section.wildcardRecords.isEmpty ? nil : "*.\(snapshot.domain)",
1638                message: section.error.map { SectionMessageViewData(text: $0, isError: true) } ??
1639                    ((section.records.isEmpty && section.wildcardRecords.isEmpty) ? SectionMessageViewData(text: "No records found", isError: false) : nil)
1640            )
1641        }
1642    }
1643
1644    static func dnssecLabel(from snapshot: LookupSnapshot) -> String? {
1645        guard let signed = snapshot.dnsSections.compactMap(\.dnssecSigned).first else { return nil }
1646        return "Resolver-reported DNSSEC (not full validation): \(signed ? "Yes" : "No")"
1647    }
1648
1649    static func ptrMessage(from snapshot: LookupSnapshot) -> SectionMessageViewData? {
1650        if let ptrRecord = snapshot.ptrRecord {
1651            return SectionMessageViewData(text: ptrRecord, isError: false)
1652        }
1653        if let ptrError = snapshot.ptrError {
1654            return SectionMessageViewData(text: ptrError, isError: ptrError != "No A record available" && ptrError != "No PTR record found")
1655        }
1656        return nil
1657    }
1658
1659    static func webCertificateRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1660        guard let sslInfo = snapshot.sslInfo else { return [] }
1661        var rows = [
1662            InfoRowViewData(label: "Common Name", value: sslInfo.commonName, tone: .primary),
1663            InfoRowViewData(label: "Issuer", value: sslInfo.issuer, tone: .primary),
1664            InfoRowViewData(label: "Valid From", value: certificateDateFormatter.string(from: sslInfo.validFrom), tone: .secondary),
1665            InfoRowViewData(label: "Valid Until", value: certificateDateFormatter.string(from: sslInfo.validUntil), tone: .secondary),
1666            InfoRowViewData(label: "Days Until Expiry", value: "\(sslInfo.daysUntilExpiry)", tone: sslInfo.daysUntilExpiry < 30 ? .failure : (sslInfo.daysUntilExpiry < 60 ? .warning : .success)),
1667            InfoRowViewData(label: "Chain Depth", value: "\(sslInfo.chainDepth)", tone: .secondary)
1668        ]
1669        if let tlsVersion = sslInfo.tlsVersion {
1670            rows.append(InfoRowViewData(label: "TLS Version", value: tlsVersion, tone: .secondary))
1671        }
1672        if let cipherSuite = sslInfo.cipherSuite {
1673            rows.append(InfoRowViewData(label: "Cipher Suite", value: cipherSuite, tone: .secondary))
1674        }
1675        if let hstsPreloaded = snapshot.hstsPreloaded {
1676            rows.append(InfoRowViewData(label: "HSTS Preload", value: hstsPreloaded ? "Preloaded" : "Not preloaded", tone: hstsPreloaded ? .success : .secondary))
1677        }
1678        return rows
1679    }
1680
1681    static func webResponseRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1682        var rows: [InfoRowViewData] = []
1683        if let httpStatusCode = snapshot.httpStatusCode {
1684            rows.append(InfoRowViewData(label: "Status", value: "\(httpStatusCode)", tone: .primary))
1685        }
1686        if let httpResponseTimeMs = snapshot.httpResponseTimeMs {
1687            rows.append(InfoRowViewData(label: "Response Time", value: "\(httpResponseTimeMs) ms", tone: .secondary))
1688        }
1689        if let httpProtocol = snapshot.httpProtocol {
1690            rows.append(InfoRowViewData(label: "Protocol", value: httpProtocol, tone: .secondary))
1691        }
1692        if let httpSecurityGrade = snapshot.httpSecurityGrade {
1693            rows.append(InfoRowViewData(label: "Security Grade", value: httpSecurityGrade, tone: securityGradeTone(httpSecurityGrade)))
1694        }
1695        if snapshot.http3Advertised {
1696            rows.append(InfoRowViewData(label: "HTTP/3", value: "Advertised", tone: .secondary))
1697        }
1698        return rows
1699    }
1700
1701    static func redirectRows(from snapshot: LookupSnapshot) -> [RedirectHopViewData] {
1702        snapshot.redirectChain.map {
1703            RedirectHopViewData(
1704                stepLabel: "\($0.stepNumber)",
1705                statusCode: "\($0.statusCode)",
1706                url: $0.url,
1707                isFinal: $0.isFinal
1708            )
1709        }
1710    }
1711
1712    static func emailRows(from snapshot: LookupSnapshot) -> [EmailRowViewData] {
1713        guard let emailSecurity = snapshot.emailSecurity else { return [] }
1714        return [
1715            EmailRowViewData(label: "SPF", status: emailSecurity.spf.found ? "Present" : "Missing", statusTone: emailSecurity.spf.found ? .success : .warning, detail: emailSecurity.spf.value ?? "No record found", auxiliaryDetail: nil),
1716            EmailRowViewData(label: "DMARC", status: emailSecurity.dmarc.found ? "Present" : "Missing", statusTone: emailSecurity.dmarc.found ? .success : .warning, detail: emailSecurity.dmarc.value ?? "No record found", auxiliaryDetail: nil),
1717            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)" }),
1718            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),
1719            EmailRowViewData(label: "BIMI", status: emailSecurity.bimi.found ? "Present" : "Missing", statusTone: emailSecurity.bimi.found ? .success : .warning, detail: emailSecurity.bimi.value ?? "No record found", auxiliaryDetail: nil)
1720        ]
1721    }
1722
1723    static func reachabilityRows(from snapshot: LookupSnapshot) -> [ReachabilityRowViewData] {
1724        snapshot.reachabilityResults.map {
1725            ReachabilityRowViewData(
1726                portLabel: "Port \($0.port)",
1727                latencyLabel: $0.latencyMs.map { "\($0) ms" } ?? "—",
1728                statusLabel: $0.reachable ? "Reachable" : "Unreachable",
1729                statusTone: $0.reachable ? .success : .failure
1730            )
1731        }
1732    }
1733
1734    static func locationRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
1735        guard let ipGeolocation = snapshot.ipGeolocation else { return [] }
1736        var rows = [InfoRowViewData(label: "IP", value: ipGeolocation.ip, tone: .primary)]
1737        if let org = ipGeolocation.org {
1738            rows.append(InfoRowViewData(label: "Org / ISP", value: org, tone: .secondary))
1739        }
1740        let location = [ipGeolocation.city, ipGeolocation.region, ipGeolocation.country_name].compactMap { $0 }.joined(separator: ", ")
1741        if !location.isEmpty {
1742            rows.append(InfoRowViewData(label: "Location", value: location, tone: .secondary))
1743        }
1744        if let latitude = ipGeolocation.latitude, let longitude = ipGeolocation.longitude {
1745            rows.append(InfoRowViewData(label: "Coordinates", value: "\(latitude), \(longitude)", tone: .secondary))
1746        }
1747        return rows
1748    }
1749
1750    static func portRows(from snapshot: LookupSnapshot, kind: PortScanKind) -> [PortScanRowViewData] {
1751        snapshot.portScanResults
1752            .filter { $0.kind == kind }
1753            .map {
1754                PortScanRowViewData(
1755                    portLabel: "\($0.port)",
1756                    service: $0.service,
1757                    statusLabel: $0.open ? "Open" : "Closed",
1758                    statusTone: $0.open ? .success : .secondary,
1759                    banner: $0.banner,
1760                    durationLabel: $0.durationMs.map { "\($0) ms" }
1761                )
1762            }
1763    }
1764
1765    static func formatBatchExportText(
1766        title: String,
1767        entries: [(snapshot: LookupSnapshot, trackedDomain: TrackedDomain?, changeSummary: DomainChangeSummary?, diffSections: [DomainDiffSection])]
1768    ) -> String {
1769        guard !entries.isEmpty else {
1770            return "\(title)\nNo results available."
1771        }
1772
1773        var lines = [title, String(repeating: "=", count: title.count), ""]
1774        for (index, entry) in entries.enumerated() {
1775            if index > 0 {
1776                lines.append("")
1777                lines.append(String(repeating: "=", count: 48))
1778                lines.append("")
1779            }
1780
1781            lines.append(
1782                formatExportText(
1783                    from: entry.snapshot,
1784                    trackedDomain: entry.trackedDomain,
1785                    changeSummary: entry.changeSummary,
1786                    diffSections: entry.diffSections
1787                )
1788            )
1789        }
1790        return lines.joined(separator: "\n")
1791    }
1792
1793    static func formatCSV(from snapshots: [LookupSnapshot]) -> String {
1794        let headers = [
1795            "domain",
1796            "availability",
1797            "primary_ip",
1798            "redirect_target",
1799            "tls_status",
1800            "http_status_grade",
1801            "email_security_summary",
1802            "last_updated"
1803        ]
1804
1805        let rows = snapshots.map { snapshot in
1806            [
1807                snapshot.domain,
1808                availabilityLabel(snapshot.availabilityResult?.status),
1809                primaryIPAddress(from: snapshot) ?? "",
1810                finalRedirectTarget(from: snapshot) ?? "",
1811                httpsSummary(from: snapshot),
1812                httpStatusGradeSummary(from: snapshot),
1813                emailSummary(from: snapshot),
1814                csvDateFormatter.string(from: snapshot.timestamp)
1815            ]
1816        }
1817
1818        return ([headers] + rows)
1819            .map { row in row.map(csvEscaped).joined(separator: ",") }
1820            .joined(separator: "\n")
1821    }
1822
1823    static func formatExportText(
1824        from snapshot: LookupSnapshot,
1825        trackedDomain: TrackedDomain?,
1826        changeSummary: DomainChangeSummary?,
1827        diffSections: [DomainDiffSection]
1828    ) -> String {
1829        let exportDateFormatter = DateFormatter()
1830        exportDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
1831
1832        var lines: [String] = [
1833            "DomainDig Export",
1834            "Domain: \(snapshot.domain)",
1835            "Date: \(exportDateFormatter.string(from: snapshot.timestamp))",
1836            "Mode: \(snapshot.isLive ? "Live" : "Snapshot")",
1837            "Resolver: \(snapshot.resolverDisplayName)",
1838            "Lookup Duration: \(durationLabel(snapshot.totalLookupDurationMs))",
1839            "Tracked: \(trackedDomain == nil ? "No" : "Yes")"
1840        ]
1841
1842        if let note = trackedDomain?.note?.nilIfEmpty {
1843            lines.append("Tracking Note: \(note)")
1844        }
1845
1846        func appendSection(_ title: String, body: () -> Void) {
1847            lines.append("")
1848            lines.append(title)
1849            lines.append(String(repeating: "-", count: title.count))
1850            body()
1851        }
1852
1853        appendSection("Summary") {
1854            for item in summaryFields(from: snapshot) {
1855                lines.append("  \(item.label): \(item.value)")
1856            }
1857            if let changeSummary {
1858                lines.append("  Change Summary: \(changeSummary.hasChanges ? "Changed" : "Unchanged")")
1859                lines.append("  Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
1860                lines.append("  Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
1861            }
1862        }
1863
1864        appendSection("Tracking") {
1865            if let trackedDomain {
1866                lines.append("  Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
1867                lines.append("  Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
1868                lines.append("  Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
1869                if let note = trackedDomain.note?.nilIfEmpty {
1870                    lines.append("  Note: \(note)")
1871                }
1872            } else {
1873                lines.append("  This domain is not currently tracked.")
1874            }
1875        }
1876
1877        appendSection("Diff Summary") {
1878            if diffSections.isEmpty {
1879                lines.append("  No comparison available")
1880            } else {
1881                for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
1882                    lines.append("  \(section.title)")
1883                    for item in section.items where item.changeType != .unchanged {
1884                        lines.append("    [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
1885                    }
1886                }
1887            }
1888        }
1889
1890        appendSection("Domain") {
1891            for row in domainRows(from: snapshot) {
1892                lines.append("  \(row.label): \(row.value)")
1893            }
1894            if snapshot.suggestions.isEmpty {
1895                lines.append("  Suggestions: None")
1896            } else {
1897                lines.append("  Suggestions:")
1898                for suggestion in snapshot.suggestions {
1899                    lines.append("    \(suggestion.domain): \(availabilityLabel(suggestion.status))")
1900                }
1901            }
1902        }
1903
1904        appendSection("DNS") {
1905            if let dnsError = snapshot.dnsError {
1906                lines.append("  Error: \(dnsError)")
1907            }
1908            if let dnssecLabel = dnssecLabel(from: snapshot) {
1909                lines.append("  \(dnssecLabel)")
1910            }
1911            for section in dnsRows(from: snapshot) {
1912                lines.append("  \(section.title)")
1913                if let message = section.message {
1914                    lines.append("    \(message.isError ? "Error" : "Info"): \(message.text)")
1915                }
1916                for row in section.rows {
1917                    lines.append("    \(row.value) (\(row.label))")
1918                }
1919                if let wildcardTitle = section.wildcardTitle {
1920                    lines.append("    \(wildcardTitle)")
1921                    for row in section.wildcardRows {
1922                        lines.append("      \(row.value) (\(row.label))")
1923                    }
1924                }
1925            }
1926            if let ptrRecord = snapshot.ptrRecord {
1927                lines.append("  PTR: \(ptrRecord)")
1928            } else if let ptrError = snapshot.ptrError {
1929                lines.append("  PTR Error: \(ptrError)")
1930            }
1931        }
1932
1933        appendSection("Web") {
1934            if let sslError = snapshot.sslError {
1935                lines.append("  TLS Error: \(sslError)")
1936            } else {
1937                for row in webCertificateRows(from: snapshot) {
1938                    lines.append("  \(row.label): \(row.value)")
1939                }
1940            }
1941
1942            if let httpHeadersError = snapshot.httpHeadersError {
1943                lines.append("  Headers Error: \(httpHeadersError)")
1944            } else {
1945                for row in webResponseRows(from: snapshot) {
1946                    lines.append("  \(row.label): \(row.value)")
1947                }
1948                if snapshot.httpHeaders.isEmpty {
1949                    lines.append("  Headers: No headers returned")
1950                } else {
1951                    lines.append("  Headers:")
1952                    for header in snapshot.httpHeaders {
1953                        lines.append("    \(header.name): \(header.value)")
1954                    }
1955                }
1956            }
1957
1958            if let redirectChainError = snapshot.redirectChainError {
1959                lines.append("  Redirect Error: \(redirectChainError)")
1960            } else if snapshot.redirectChain.isEmpty {
1961                lines.append("  Redirects: No redirect data available")
1962            } else {
1963                lines.append("  Redirects:")
1964                for hop in redirectRows(from: snapshot) {
1965                    lines.append("    \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
1966                }
1967            }
1968        }
1969
1970        appendSection("Email") {
1971            if let emailSecurityError = snapshot.emailSecurityError {
1972                lines.append("  Error: \(emailSecurityError)")
1973            } else if emailRows(from: snapshot).isEmpty {
1974                lines.append("  No email security records found")
1975            } else {
1976                for row in emailRows(from: snapshot) {
1977                    lines.append("  \(row.label): \(row.status)")
1978                    lines.append("    \(row.detail)")
1979                    if let auxiliaryDetail = row.auxiliaryDetail {
1980                        lines.append("    \(auxiliaryDetail)")
1981                    }
1982                }
1983            }
1984        }
1985
1986        appendSection("Network") {
1987            if let reachabilityError = snapshot.reachabilityError {
1988                lines.append("  Reachability Error: \(reachabilityError)")
1989            } else if reachabilityRows(from: snapshot).isEmpty {
1990                lines.append("  Reachability: No results")
1991            } else {
1992                lines.append("  Reachability:")
1993                for row in reachabilityRows(from: snapshot) {
1994                    lines.append("    \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
1995                }
1996            }
1997
1998            if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
1999                lines.append("  Location Error: \(ipGeolocationError)")
2000            } else if locationRows(from: snapshot).isEmpty {
2001                lines.append("  Location: No data")
2002            } else {
2003                lines.append("  Location:")
2004                for row in locationRows(from: snapshot) {
2005                    lines.append("    \(row.label): \(row.value)")
2006                }
2007            }
2008
2009            if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
2010                lines.append("  Port Scan Error: \(portScanError)")
2011            }
2012
2013            lines.append("  Standard Ports:")
2014            let standardRows = portRows(from: snapshot, kind: .standard)
2015            if standardRows.isEmpty {
2016                lines.append("    No results")
2017            } else {
2018                for row in standardRows {
2019                    lines.append("    \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
2020                    if let banner = row.banner {
2021                        lines.append("      Banner: \(banner)")
2022                    }
2023                }
2024            }
2025
2026            lines.append("  Custom Ports:")
2027            let customRows = portRows(from: snapshot, kind: .custom)
2028            if customRows.isEmpty {
2029                lines.append("    No results")
2030            } else {
2031                for row in customRows {
2032                    lines.append("    \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
2033                    if let banner = row.banner {
2034                        lines.append("      Banner: \(banner)")
2035                    }
2036                }
2037            }
2038        }
2039
2040        return lines.joined(separator: "\n")
2041    }
2042
2043    private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
2044        snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
2045    }
2046
2047    private static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
2048        snapshot.redirectChain.last?.url
2049    }
2050
2051    private static func httpStatusGradeSummary(from snapshot: LookupSnapshot) -> String {
2052        let parts = [snapshot.httpStatusCode.map(String.init), snapshot.httpSecurityGrade].compactMap { $0 }
2053        if !parts.isEmpty {
2054            return parts.joined(separator: " / ")
2055        }
2056        return snapshot.httpHeadersError ?? "Unavailable"
2057    }
2058
2059    private static func httpsSummary(from snapshot: LookupSnapshot) -> String {
2060        if snapshot.sslInfo != nil {
2061            return "Valid"
2062        }
2063        if let sslError = snapshot.sslError {
2064            return sslError.localizedCaseInsensitiveContains("certificate") ? "Invalid" : "Failed"
2065        }
2066        return "Unavailable"
2067    }
2068
2069    private static func httpsSummaryTone(from snapshot: LookupSnapshot) -> ResultTone {
2070        if snapshot.sslInfo != nil {
2071            return .success
2072        }
2073        return snapshot.sslError == nil ? .secondary : .failure
2074    }
2075
2076    private static func emailSummary(from snapshot: LookupSnapshot) -> String {
2077        guard let emailSecurity = snapshot.emailSecurity else {
2078            return snapshot.emailSecurityError ?? "Unavailable"
2079        }
2080        return "SPF \(emailSecurity.spf.found ? "Yes" : "No") / DMARC \(emailSecurity.dmarc.found ? "Yes" : "No")"
2081    }
2082
2083    private static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
2084        switch status {
2085        case .available:
2086            return "Available"
2087        case .registered:
2088            return "Registered"
2089        case .unknown, .none:
2090            return "Unknown"
2091        }
2092    }
2093
2094    private static func availabilityTone(_ status: DomainAvailabilityStatus?) -> ResultTone {
2095        switch status {
2096        case .available:
2097            return .success
2098        case .registered:
2099            return .warning
2100        case .unknown, .none:
2101            return .secondary
2102        }
2103    }
2104
2105    private static func securityGradeTone(_ grade: String) -> ResultTone {
2106        switch grade {
2107        case "A", "B":
2108            return .success
2109        case "C":
2110            return .warning
2111        case "D", "F":
2112            return .failure
2113        default:
2114            return .secondary
2115        }
2116    }
2117
2118    private static func durationLabel(_ durationMs: Int?) -> String {
2119        durationMs.map { "\($0) ms" } ?? "Unavailable"
2120    }
2121
2122    private static let certificateDateFormatter: DateFormatter = {
2123        let formatter = DateFormatter()
2124        formatter.dateStyle = .medium
2125        formatter.timeStyle = .short
2126        return formatter
2127    }()
2128
2129    private static let csvDateFormatter: ISO8601DateFormatter = {
2130        let formatter = ISO8601DateFormatter()
2131        formatter.formatOptions = [.withInternetDateTime]
2132        return formatter
2133    }()
2134
2135    private static func csvEscaped(_ value: String) -> String {
2136        let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
2137        return "\"\(escaped)\""
2138    }
2139}
2140
2141private extension String {
2142    var nonEmpty: String? {
2143        isEmpty ? nil : self
2144    }
2145
2146    var nilIfEmpty: String? {
2147        isEmpty ? nil : self
2148    }
2149}