DomainDig/DomainViewModel.swift

9384a668bf36f23f71e25d05b490d1040d308845
domain-dig/DomainDig/DomainViewModel.swift history · blame · raw

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