DomainDig/DomainViewModel.swift

7b41195620eadd54d25fa98dcd36735cba906ba3
domain-dig/DomainDig/DomainViewModel.swift history · blame · raw

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