DomainDig/DomainViewModel.swift

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

3438 lines · 146426 bytes

171 symbols in this file
   1import Foundation
   2import SwiftUI
   3import UserNotifications
   4
   5enum ResultTone {
   6    case primary
   7    case secondary
   8    case success
   9    case warning
  10    case failure
  11}
  12
  13struct SummaryFieldViewData: Identifiable {
  14    let id = UUID()
  15    let label: String
  16    let value: String
  17    let tone: ResultTone
  18}
  19
  20/// How VoiceOver should pronounce a row's value.
  21///
  22/// DNS records, cipher suites, and the like are read as prose by default, which
  23/// mangles load-bearing punctuation (`;`, `~`, `_`) and technical tokens. See
  24/// `Docs/ACCESSIBILITY.md`.
  25enum RowSpeechStyle {
  26    /// Normal prose.
  27    case plain
  28    /// Record values and identifiers: include punctuation, use code heuristics.
  29    case technical
  30}
  31
  32struct InfoRowViewData: Identifiable {
  33    let id = UUID()
  34    let label: String
  35    let value: String
  36    let tone: ResultTone
  37    var speechStyle: RowSpeechStyle = .plain
  38}
  39
  40struct SectionMessageViewData {
  41    let text: String
  42    let isError: Bool
  43}
  44
  45struct DNSRecordSectionViewData: Identifiable {
  46    let id = UUID()
  47    let title: String
  48    let rows: [InfoRowViewData]
  49    let wildcardRows: [InfoRowViewData]
  50    let wildcardTitle: String?
  51    let message: SectionMessageViewData?
  52}
  53
  54struct EmailRowViewData: Identifiable {
  55    let id = UUID()
  56    let label: String
  57    let status: String
  58    let statusTone: ResultTone
  59    let detail: String
  60    let auxiliaryDetail: String?
  61}
  62
  63struct RedirectHopViewData: Identifiable {
  64    let id = UUID()
  65    let stepLabel: String
  66    let statusCode: String
  67    let url: String
  68    let isFinal: Bool
  69}
  70
  71struct ReachabilityRowViewData: Identifiable {
  72    let id = UUID()
  73    let portLabel: String
  74    let latencyLabel: String
  75    let statusLabel: String
  76    let statusTone: ResultTone
  77}
  78
  79struct PortScanRowViewData: Identifiable {
  80    let id = UUID()
  81    let portLabel: String
  82    let service: String
  83    let statusLabel: String
  84    let statusTone: ResultTone
  85    let banner: String?
  86    let durationLabel: String?
  87}
  88
  89struct SubdomainRowViewData: Identifiable {
  90    let id: String
  91    let hostname: String
  92    let isInteresting: Bool
  93
  94    init(hostname: String, isInteresting: Bool) {
  95        self.id = hostname
  96        self.hostname = hostname
  97        self.isInteresting = isInteresting
  98    }
  99}
 100
 101struct DomainSuggestionViewData: Identifiable {
 102    let id: UUID
 103    let domain: String
 104    let availabilityStatus: DomainAvailabilityStatus
 105    let status: String
 106    let tone: ResultTone
 107}
 108
 109private struct BatchLookupPayload {
 110    let snapshot: LookupSnapshot
 111}
 112
 113@MainActor
 114@Observable
 115final class DomainViewModel {
 116    var domain: String = ""
 117    var bulkInput: String = ""
 118    var domainInputError: String?
 119    /// What the bulk path skipped, for the same reason `domainInputError`
 120    /// exists for the single one.
 121    var bulkInputError: String?
 122
 123    // MARK: Section state
 124
 125    /// Each section's value, phase and error as one stored property, so the
 126    /// three are written together or not at all. There were 20 `*Loading`
 127    /// flags and 19 `*Error` strings before, independently assignable (A2).
 128    ///
 129    /// The accessors below keep the names every reader already uses. They are
 130    /// a staging layer: the next step is views reading the state directly, as
 131    /// the Web and Network slices already do.
 132    var dnsState = SectionState<[DNSSection]>()
 133    var availabilityState = SectionState<DomainAvailabilityResult>()
 134    var suggestionsState = SectionState<[DomainSuggestionResult]>()
 135    var sslState = SectionState<SSLCertificateInfo>()
 136    var hstsState = SectionState<Bool>()
 137    var httpHeadersState = SectionState<[HTTPHeader]>()
 138    var reachabilityState = SectionState<[PortReachability]>()
 139    var ipGeolocationState = SectionState<IPGeolocation>()
 140    var emailSecurityState = SectionState<EmailSecurityResult>()
 141    var ownershipState = SectionState<DomainOwnership>()
 142    var ownershipHistoryState = SectionState<[DomainOwnershipHistoryEvent]>()
 143    var ptrState = SectionState<String>()
 144    var redirectChainState = SectionState<[RedirectHop]>()
 145    var subdomainsState = SectionState<[DiscoveredSubdomain]>()
 146    var extendedSubdomainsState = SectionState<[DiscoveredSubdomain]>()
 147    var dnsHistoryState = SectionState<[DNSHistoryEvent]>()
 148    var domainPricingState = SectionState<DomainPricingInsight>()
 149    var reputationState = SectionState<DomainReputationResult>()
 150    var portScanState = SectionState<[PortScanResult]>()
 151    var customPortScanState = SectionState<[PortScanResult]>()
 152
 153    var dnsSections: [DNSSection] { dnsState.items }
 154    var dnsLoading: Bool { dnsState.isLoading }
 155    var dnsError: String? { dnsState.error }
 156
 157    var availabilityResult: DomainAvailabilityResult? { availabilityState.value }
 158    var availabilityLoading: Bool { availabilityState.isLoading }
 159
 160    var suggestions: [DomainSuggestionResult] { suggestionsState.items }
 161    var suggestionsLoading: Bool { suggestionsState.isLoading }
 162
 163    var sslInfo: SSLCertificateInfo? { sslState.value }
 164    var sslLoading: Bool { sslState.isLoading }
 165    var sslError: String? { sslState.error }
 166
 167    var hstsPreloaded: Bool? { hstsState.value }
 168    var hstsLoading: Bool { hstsState.isLoading }
 169
 170    var httpHeaders: [HTTPHeader] { httpHeadersState.items }
 171    var httpHeadersLoading: Bool { httpHeadersState.isLoading }
 172    var httpHeadersError: String? { httpHeadersState.error }
 173
 174    var reachabilityResults: [PortReachability] { reachabilityState.items }
 175    var reachabilityLoading: Bool { reachabilityState.isLoading }
 176    var reachabilityError: String? { reachabilityState.error }
 177
 178    var ipGeolocation: IPGeolocation? { ipGeolocationState.value }
 179    var ipGeolocationLoading: Bool { ipGeolocationState.isLoading }
 180    var ipGeolocationError: String? { ipGeolocationState.error }
 181
 182    var emailSecurity: EmailSecurityResult? { emailSecurityState.value }
 183    var emailSecurityLoading: Bool { emailSecurityState.isLoading }
 184    var emailSecurityError: String? { emailSecurityState.error }
 185
 186    var ownershipResult: DomainOwnership? { ownershipState.value }
 187    var ownershipLoading: Bool { ownershipState.isLoading }
 188    var ownershipError: String? { ownershipState.error }
 189
 190    var ownershipHistory: [DomainOwnershipHistoryEvent] { ownershipHistoryState.items }
 191    var ownershipHistoryLoading: Bool { ownershipHistoryState.isLoading }
 192    var ownershipHistoryError: String? { ownershipHistoryState.error }
 193
 194    var ptrRecord: String? { ptrState.value }
 195    var ptrLoading: Bool { ptrState.isLoading }
 196    var ptrError: String? { ptrState.error }
 197
 198    var redirectChain: [RedirectHop] { redirectChainState.items }
 199    var redirectChainLoading: Bool { redirectChainState.isLoading }
 200    var redirectChainError: String? { redirectChainState.error }
 201
 202    var subdomains: [DiscoveredSubdomain] { subdomainsState.items }
 203    var subdomainsLoading: Bool { subdomainsState.isLoading }
 204    var subdomainsError: String? { subdomainsState.error }
 205
 206    var extendedSubdomains: [DiscoveredSubdomain] { extendedSubdomainsState.items }
 207    var extendedSubdomainsLoading: Bool { extendedSubdomainsState.isLoading }
 208    var extendedSubdomainsError: String? { extendedSubdomainsState.error }
 209
 210    var dnsHistory: [DNSHistoryEvent] { dnsHistoryState.items }
 211    var dnsHistoryLoading: Bool { dnsHistoryState.isLoading }
 212    var dnsHistoryError: String? { dnsHistoryState.error }
 213
 214    var domainPricing: DomainPricingInsight? { domainPricingState.value }
 215    var domainPricingLoading: Bool { domainPricingState.isLoading }
 216    var domainPricingError: String? { domainPricingState.error }
 217
 218    var reputation: DomainReputationResult? { reputationState.value }
 219    var reputationLoading: Bool { reputationState.isLoading }
 220    var reputationError: String? { reputationState.error }
 221
 222    var portScanResults: [PortScanResult] { portScanState.items }
 223    var portScanLoading: Bool { portScanState.isLoading }
 224    var portScanError: String? { portScanState.error }
 225
 226    var customPortResults: [PortScanResult] { customPortScanState.items }
 227    var customPortScanLoading: Bool { customPortScanState.isLoading }
 228    var customPortScanError: String? { customPortScanState.error }
 229
 230    var httpSecurityGrade: String?
 231    var httpStatusCode: Int?
 232    var httpResponseTimeMs: Int?
 233    var httpProtocol: String?
 234    var http3Advertised = false
 235
 236    var hasRun = false
 237    private(set) var searchedDomain: String = ""
 238    private(set) var lastLookupDurationMs: Int?
 239    private(set) var currentDiffSections: [DomainDiffSection] = []
 240    private(set) var currentChangeSummary: DomainChangeSummary?
 241    private(set) var ownershipDiff: [DomainDiffItem] = []
 242    private(set) var refreshingTrackedDomainID: UUID?
 243    private(set) var rerunNavigationToken = UUID()
 244    private(set) var batchResults: [BatchLookupResult] = []
 245    private(set) var batchLookupSource: BatchLookupSource = .manual
 246    private(set) var batchCurrentDomain: String?
 247    private(set) var batchCompletedCount = 0
 248    private(set) var batchTotalCount = 0
 249    private(set) var batchLookupRunning = false
 250    var latestBatchSweepSummary: BatchSweepSummary?
 251    var latestWorkflowRunSummary: WorkflowRunSummary?
 252    private(set) var notificationsAuthorized = false
 253
 254    private var lookupTask: Task<Void, Never>?
 255    private var customPortScanTask: Task<Void, Never>?
 256    private var batchTask: Task<Void, Never>?
 257    private var activeLookupID = UUID()
 258    private var lookupStartedAt: Date?
 259    private var activeBatchDomains: [String] = []
 260    private var lastBatchStartedAt: Date?
 261    var activeWorkflowRunID: UUID?
 262    var activeWorkflowRunName: String?
 263    private var historyPersistenceSuspended = false
 264    private var trackedDomainsPersistenceSuspended = false
 265    private var historyPersistenceDirty = false
 266    private var trackedDomainsPersistenceDirty = false
 267    private let reportBuilder = DomainReportBuilder()
 268    private let inspectionService = DomainInspectionService()
 269    private(set) var currentResultSource: LookupResultSource = .live
 270    private(set) var currentCachedSections: [LookupSectionKind] = []
 271    private(set) var currentStatusMessage: String?
 272    private(set) var currentSnapshotTimestamp = Date()
 273    private(set) var currentHistoryEntryID: UUID?
 274    /// The metadata the current lookup produced, in preference to whatever the
 275    /// saved entry holds. Nil outside a lookup, when the saved entry is the
 276    /// only source there is.
 277    private(set) var currentInspectionMetadata: InspectionMetadata?
 278    private(set) var currentReport: DomainReport?
 279
 280    private static let recentSearchesKey = "recentSearches"
 281    private static let maxRecent = 20
 282    var recentSearches: [String]
 283
 284
 285    private static let trackedDomainsKey = "trackedDomains"
 286    private static let legacyWatchedDomainsKey = "watchedDomains"
 287    var trackedDomains: [TrackedDomain]
 288
 289    private static let historyKey = "lookupHistory"
 290    var history: [HistoryEntry]
 291    var auditSessions: [AuditSession]
 292    private static let workflowsKey = "domainWorkflows"
 293    var workflows: [DomainWorkflow]
 294    var historySearchText = ""
 295    var historyDateFilter: HistoryDateFilter = .all
 296    var historyChangeFilter: ChangeFilterOption = .all
 297    var historySortOption: HistorySortOption = .newest
 298    var timelineGrouping: TimelineGroupingOption = .relativeDay
 299    var timelineDomainFilter = ""
 300    var watchlistSearchText = ""
 301    var watchlistFilter: WatchlistFilterOption = .all
 302    var watchlistSortOption: WatchlistSortOption = .pinned
 303    var watchlistTagFilter: String?
 304    var watchlistSavedViews: [WatchlistSavedView]
 305    var dashboardSearchText = ""
 306    var dashboardFilter: PortfolioFilterOption = .all
 307    var monitoringSettings: MonitoringSettings
 308    var monitoringLogs: [MonitoringLog]
 309    var monitoringRunInProgress = false
 310    var monitoringStatusMessage: String?
 311    var monitoringNotificationStatus: UNAuthorizationStatus = .notDetermined
 312    var dataLifecycleSummary: DataLifecycleSummary
 313    var portabilityStatusMessage: String?
 314    var upgradePrompt: UpgradePromptContext?
 315    var isPaywallPresented = false
 316    var selectedSnapshotIDs = Set<UUID>()
 317    var activeDomainDiff: DomainDiff?
 318    var activeDiffChangeIndex = 0
 319
 320    private static let historyAutoPruneKey = "historyAutoPrune"
 321    var historyAutoPruneOption: HistoryAutoPruneOption
 322
 323    /// The store every persisted property is read from and written back to.
 324    /// Injected so a test can drive the whole lifecycle — history pruning,
 325    /// tracking limits, batch state — against a scratch store instead of the
 326    /// one the app is using.
 327    let defaults: UserDefaults
 328
 329    /// History lives in files rather than in `defaults`, so the directory is
 330    /// injected alongside the store it used to be part of.
 331    let historyLocation: HistoryFileStore.Location
 332
 333    init(
 334        defaults: UserDefaults = .standard,
 335        historyLocation: HistoryFileStore.Location = .default
 336    ) {
 337        self.defaults = defaults
 338        self.historyLocation = historyLocation
 339        recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
 340        trackedDomains = DomainViewModel.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
 341        history = DomainViewModel.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
 342        auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
 343        workflows = DomainViewModel.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
 344        watchlistSavedViews = DomainViewModel.loadWatchlistSavedViews(defaults: defaults)
 345        monitoringSettings = MonitoringStorage.loadSettings(defaults: defaults)
 346        monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
 347        dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
 348        historyAutoPruneOption = DomainViewModel.loadHistoryAutoPruneOption(defaults: defaults)
 349    }
 350
 351    var trimmedDomain: String {
 352        domain
 353            .trimmingCharacters(in: .whitespacesAndNewlines)
 354            .replacingOccurrences(of: "https://", with: "")
 355            .replacingOccurrences(of: "http://", with: "")
 356            .components(separatedBy: "/").first ?? ""
 357    }
 358
 359    var resultsLoaded: Bool {
 360        guard hasRun else { return false }
 361        return [
 362            dnsState.isSettled,
 363            availabilityState.isSettled,
 364            suggestionsState.isSettled,
 365            sslState.isSettled,
 366            hstsState.isSettled,
 367            httpHeadersState.isSettled,
 368            reachabilityState.isSettled,
 369            ipGeolocationState.isSettled,
 370            emailSecurityState.isSettled,
 371            ownershipState.isSettled,
 372            ptrState.isSettled,
 373            redirectChainState.isSettled,
 374            subdomainsState.isSettled,
 375            portScanState.isSettled,
 376            !customPortScanState.isLoading
 377        ].allSatisfy { $0 }
 378    }
 379
 380    /// A single lookup is in flight. `hasRun` is set when one starts and the
 381    /// sections settle as they land, so this is the window in which cancelling
 382    /// means something — the counterpart to `batchLookupRunning`.
 383    var singleLookupRunning: Bool {
 384        hasRun && !resultsLoaded
 385    }
 386
 387    var activeLoadingLabels: [String] {
 388        var labels: [String] = []
 389        if availabilityLoading { labels.append("Availability") }
 390        if dnsLoading { labels.append("DNS") }
 391        if sslLoading || hstsLoading { labels.append("TLS") }
 392        if httpHeadersLoading { labels.append("HTTP") }
 393        if ownershipLoading { labels.append("Ownership") }
 394        if ownershipHistoryLoading { labels.append("Ownership History") }
 395        if emailSecurityLoading { labels.append("Email") }
 396        if subdomainsLoading { labels.append("Subdomains") }
 397        if extendedSubdomainsLoading { labels.append("Extended Subdomains") }
 398        if dnsHistoryLoading { labels.append("DNS History") }
 399        if domainPricingLoading { labels.append("Pricing") }
 400        if redirectChainLoading { labels.append("Redirects") }
 401        if reachabilityLoading { labels.append("Reachability") }
 402        if ipGeolocationLoading { labels.append("Geolocation") }
 403        if ptrLoading { labels.append("PTR") }
 404        if portScanLoading { labels.append("Port Scan") }
 405        if customPortScanLoading { labels.append("Custom Ports") }
 406        return labels
 407    }
 408
 409    var isCloudflareProxied: Bool {
 410        httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
 411    }
 412
 413    var sortedTrackedDomains: [TrackedDomain] {
 414        sortedTrackedDomains(from: trackedDomains, using: .pinned)
 415    }
 416
 417    var filteredHistory: [HistoryEntry] {
 418        let calendar = Calendar.current
 419        let now = Date()
 420        let query = historySearchText.trimmingCharacters(in: .whitespacesAndNewlines)
 421
 422        return history
 423            .lazy
 424            .filter { entry in
 425                query.isEmpty || entry.domain.localizedCaseInsensitiveContains(query)
 426            }
 427            .filter { entry in
 428                switch self.historyDateFilter {
 429                case .today:
 430                    return calendar.isDate(entry.timestamp, inSameDayAs: now)
 431                case .last7Days:
 432                    guard let startDate = calendar.date(byAdding: .day, value: -7, to: now) else { return true }
 433                    return entry.timestamp >= startDate
 434                case .all:
 435                    return true
 436                }
 437            }
 438            .filter { entry in
 439                switch self.historyChangeFilter {
 440                case .all:
 441                    return true
 442                case .changed:
 443                    return entry.changeSummary?.hasChanges == true
 444                case .unchanged:
 445                    return entry.changeSummary?.hasChanges != true
 446                }
 447            }
 448            .sorted(by: historySortPredicate)
 449    }
 450
 451    var filteredTrackedDomains: [TrackedDomain] {
 452        let query = watchlistSearchText.trimmingCharacters(in: .whitespacesAndNewlines)
 453        let filtered = trackedDomains.filter { trackedDomain in
 454            if !query.isEmpty, !trackedDomain.domain.localizedCaseInsensitiveContains(query) {
 455                return false
 456            }
 457
 458            if let watchlistTagFilter, !trackedDomain.tags.contains(watchlistTagFilter) {
 459                return false
 460            }
 461
 462            switch watchlistFilter {
 463            case .all:
 464                return true
 465            case .pinnedOnly:
 466                return trackedDomain.isPinned
 467            case .changedOnly:
 468                return trackedDomain.lastChangeSummary?.hasChanges == true
 469            }
 470        }
 471
 472        return sortedTrackedDomains(from: filtered, using: watchlistSortOption)
 473    }
 474
 475    /// Builds the dashboard. Uncached, deliberately: the cache this replaces
 476    /// was keyed on a signature of every tracked domain, the last 250 history
 477    /// rows and the last 100 monitoring logs, built with
 478    /// `.formatted(.number.precision(.fractionLength(3)))` — roughly 350
 479    /// interpolations per access, and the dashboard reads this more than twenty
 480    /// times per render, so checking the cache cost far more than the build it
 481    /// was avoiding (A4).
 482    ///
 483    /// Callers that need it more than once should read it once and filter with
 484    /// `filtered(by:searchText:)`, which is what `DashboardView` does.
 485    var portfolioDashboardData: PortfolioDashboardData {
 486        let domainStates = buildPortfolioDomainStates()
 487        let recentActivity = buildPortfolioActivity(from: domainStates)
 488        let attentionRequired = buildAttentionQueue(from: domainStates)
 489        let expiringSoon = domainStates
 490            .filter { $0.certificateExpiryState != .none }
 491            .sorted {
 492                ($0.certificateDaysRemaining ?? .max, $0.trackedDomain.domain)
 493                    < ($1.certificateDaysRemaining ?? .max, $1.trackedDomain.domain)
 494            }
 495        let groups = PortfolioDashboardData.groups(from: domainStates)
 496        let snapshot = PortfolioSnapshot(
 497            totalDomains: domainStates.count,
 498            healthyCount: domainStates.filter { $0.health == .healthy }.count,
 499            warningCount: domainStates.filter { $0.health == .warning }.count,
 500            criticalCount: domainStates.filter { $0.health == .critical }.count,
 501            changedLast24h: domainStates.filter {
 502                guard let lastChangeDate = $0.lastChangeDate else { return false }
 503                return Date().timeIntervalSince(lastChangeDate) <= 24 * 60 * 60
 504            }.count,
 505            expiringSoonCount: expiringSoon.count,
 506            unreachableCount: domainStates.filter(\.isUnreachable).count
 507        )
 508        return PortfolioDashboardData(
 509            snapshot: snapshot,
 510            domainStates: domainStates,
 511            recentActivity: recentActivity,
 512            attentionRequired: attentionRequired,
 513            expiringSoon: expiringSoon,
 514            groups: groups
 515        )
 516    }
 517
 518    var timelineDomains: [String] {
 519        let query = timelineDomainFilter.trimmingCharacters(in: .whitespacesAndNewlines)
 520        let domains = history.map(\.domain)
 521        let filtered = query.isEmpty
 522            ? domains
 523            : domains.filter { $0.localizedCaseInsensitiveContains(query) }
 524        return Array(Set(filtered)).sorted()
 525    }
 526
 527    var batchProgressLabel: String {
 528        guard batchTotalCount > 0 else { return "No active batch" }
 529        if !batchLookupRunning, batchCompletedCount >= batchTotalCount {
 530            return "\(batchCompletedCount)/\(batchTotalCount) • Complete"
 531        }
 532        let domainLabel = activeBatchDomains.first ?? batchCurrentDomain ?? "Preparing"
 533        return "\(batchCompletedCount)/\(batchTotalCount) • \(domainLabel)"
 534    }
 535
 536    var currentBatchResultEntries: [HistoryEntry] {
 537        batchResults.compactMap { result in
 538            guard let historyEntryID = result.historyEntryID else { return nil }
 539            return history.first(where: { $0.id == historyEntryID })
 540        }
 541    }
 542
 543    var currentTrackedDomain: TrackedDomain? {
 544        guard !searchedDomain.isEmpty else { return nil }
 545        return trackedDomain(for: searchedDomain)
 546    }
 547
 548    var currentDomainWorkflows: [DomainWorkflow] {
 549        guard !searchedDomain.isEmpty else { return [] }
 550        return workflowsContaining(domain: searchedDomain)
 551    }
 552
 553    var isCurrentDomainTracked: Bool {
 554        currentTrackedDomain != nil
 555    }
 556
 557    var trackingLimitMessage: String? {
 558        FeatureAccessService.trackedDomainLimitMessage(currentCount: trackedDomains.count)
 559    }
 560
 561    var canTrackCurrentDomain: Bool {
 562        FeatureAccessService.canAddTrackedDomain(currentCount: trackedDomains.count)
 563    }
 564
 565    var resolverDisplayName: String {
 566        DNSLookupService.currentResolverDisplayName()
 567    }
 568
 569    var resolverURLString: String {
 570        DNSLookupService.currentResolverURLString()
 571    }
 572
 573    var allPortScanResults: [PortScanResult] {
 574        (portScanResults + customPortResults).sorted {
 575            if $0.kind == $1.kind {
 576                return $0.port < $1.port
 577            }
 578            return $0.kind == .standard
 579        }
 580    }
 581
 582    var currentSnapshot: LookupSnapshot {
 583        LookupSnapshot(
 584            historyEntryID: currentHistoryEntryID,
 585            domain: searchedDomain,
 586            timestamp: currentSnapshotTimestamp,
 587            trackedDomainID: currentTrackedDomain?.id,
 588            note: currentHistoryEntry?.note ?? currentTrackedDomain?.note,
 589            appVersion: AppVersion.current,
 590            resolverDisplayName: resolverDisplayName,
 591            resolverURLString: resolverURLString,
 592            dataSources: currentInspectionMetadata?.dataSources ?? currentHistoryEntry?.dataSources ?? [],
 593            provenanceBySection: currentInspectionMetadata?.provenanceBySection ?? currentHistoryEntry?.provenanceBySection ?? [:],
 594            availabilityConfidence: currentInspectionMetadata?.availabilityConfidence ?? currentHistoryEntry?.availabilityConfidence,
 595            ownershipConfidence: currentInspectionMetadata?.ownershipConfidence ?? currentHistoryEntry?.ownershipConfidence,
 596            subdomainConfidence: currentInspectionMetadata?.subdomainConfidence ?? currentHistoryEntry?.subdomainConfidence,
 597            emailSecurityConfidence: currentInspectionMetadata?.emailSecurityConfidence ?? currentHistoryEntry?.emailSecurityConfidence,
 598            geolocationConfidence: currentInspectionMetadata?.geolocationConfidence ?? currentHistoryEntry?.geolocationConfidence,
 599            errorDetails: currentInspectionMetadata?.errorDetails ?? currentHistoryEntry?.errorDetails ?? [:],
 600            isPartialSnapshot: currentInspectionMetadata?.isPartialSnapshot ?? currentHistoryEntry?.isPartialSnapshot ?? false,
 601            validationIssues: currentInspectionMetadata?.validationIssues ?? currentHistoryEntry?.validationIssues ?? [],
 602            totalLookupDurationMs: lastLookupDurationMs,
 603            snapshotIndex: currentInspectionMetadata?.snapshotIndex ?? currentHistoryEntry?.snapshotIndex,
 604            previousSnapshotID: currentInspectionMetadata?.previousSnapshotID ?? currentHistoryEntry?.previousSnapshotID,
 605            changeCount: currentHistoryEntry?.changeCount ?? currentChangeSummary?.changedSections.count ?? 0,
 606            severitySummary: currentHistoryEntry?.severitySummary ?? currentChangeSummary?.severity,
 607            dnsSections: dnsSections,
 608            dnsError: dnsError,
 609            availabilityResult: availabilityResult,
 610            suggestions: suggestions,
 611            sslInfo: sslInfo,
 612            sslError: sslError,
 613            hstsPreloaded: hstsPreloaded,
 614            httpHeaders: httpHeaders,
 615            httpSecurityGrade: httpSecurityGrade,
 616            httpStatusCode: httpStatusCode,
 617            httpResponseTimeMs: httpResponseTimeMs,
 618            httpProtocol: httpProtocol,
 619            http3Advertised: http3Advertised,
 620            httpHeadersError: httpHeadersError,
 621            reachabilityResults: reachabilityResults,
 622            reachabilityError: reachabilityError,
 623            ipGeolocation: ipGeolocation,
 624            ipGeolocationError: ipGeolocationError,
 625            emailSecurity: emailSecurity,
 626            emailSecurityError: emailSecurityError,
 627            ownership: ownershipResult,
 628            ownershipError: ownershipError,
 629            ownershipHistory: ownershipHistory,
 630            ownershipHistoryError: ownershipHistoryError,
 631            inferredProvider: currentHistoryEntry?.inferredProvider ?? currentReport?.inferredProvider,
 632            priorProviders: currentHistoryEntry?.priorProviders ?? currentReport?.priorProviders ?? [],
 633            domainClassification: currentHistoryEntry?.domainClassification ?? currentReport?.domainClassification,
 634            ownershipTransitions: currentHistoryEntry?.ownershipTransitions ?? currentReport?.ownershipTransitions ?? [],
 635            hostingTransitions: currentHistoryEntry?.hostingTransitions ?? currentReport?.hostingTransitions ?? [],
 636            subdomainHistory: currentHistoryEntry?.subdomainHistory ?? currentReport?.subdomainHistory ?? [],
 637            riskSignals: currentHistoryEntry?.riskSignals ?? currentReport?.riskSignals ?? [],
 638            intelligenceTimeline: currentHistoryEntry?.intelligenceTimeline ?? currentReport?.intelligenceTimeline ?? [],
 639            ptrRecord: ptrRecord,
 640            ptrError: ptrError,
 641            redirectChain: redirectChain,
 642            redirectChainError: redirectChainError,
 643            subdomains: subdomains,
 644            subdomainsError: subdomainsError,
 645            extendedSubdomains: extendedSubdomains,
 646            extendedSubdomainsError: extendedSubdomainsError,
 647            dnsHistory: dnsHistory,
 648            dnsHistoryError: dnsHistoryError,
 649            domainPricing: domainPricing,
 650            domainPricingError: domainPricingError,
 651            reputation: reputation,
 652            reputationError: reputationError,
 653            portScanResults: allPortScanResults,
 654            portScanError: combinedPortScanError,
 655            changeSummary: currentChangeSummary,
 656            resultSource: currentResultSource,
 657            cachedSections: currentCachedSections,
 658            statusMessage: currentStatusMessage
 659        )
 660    }
 661
 662    private var currentHistoryEntry: HistoryEntry? {
 663        guard let currentHistoryEntryID else { return nil }
 664        return history.first(where: { $0.id == currentHistoryEntryID })
 665    }
 666
 667    var currentRiskAssessment: DomainRiskAssessment? {
 668        currentReport?.riskAssessment
 669    }
 670
 671    var currentInsights: [String] {
 672        currentReport?.insights ?? []
 673    }
 674
 675    var currentSubdomainGroups: [SubdomainGroup] {
 676        currentReport?.subdomainGroups ?? []
 677    }
 678
 679    var currentDNSPatterns: DNSPatternSummary? {
 680        currentReport?.dns.patternSummary
 681    }
 682
 683    var currentEmailAssessment: EmailSecuritySummary? {
 684        currentReport?.email
 685    }
 686
 687    var currentTLSSummary: WebResultSummary? {
 688        currentReport?.web
 689    }
 690
 691    var combinedSubdomains: [DiscoveredSubdomain] {
 692        let existingHosts = Set(subdomains.map { $0.hostname.lowercased() })
 693        return subdomains + extendedSubdomains.filter { !existingHosts.contains($0.hostname.lowercased()) }
 694    }
 695
 696    var summaryFields: [SummaryFieldViewData] {
 697        Self.summaryFields(from: currentSnapshot)
 698    }
 699
 700    var domainRows: [InfoRowViewData] {
 701        Self.domainRows(from: currentSnapshot)
 702    }
 703
 704    var dnsRows: [DNSRecordSectionViewData] {
 705        Self.dnsRows(from: currentSnapshot)
 706    }
 707
 708    var suggestionRows: [DomainSuggestionViewData] {
 709        Self.suggestionRows(from: currentSnapshot)
 710    }
 711
 712    var dnssecLabel: String? {
 713        Self.dnssecLabel(from: currentSnapshot)
 714    }
 715
 716    var ptrMessage: SectionMessageViewData? {
 717        Self.ptrMessage(from: currentSnapshot)
 718    }
 719
 720    /// The same two slices built from a stored snapshot, for the history
 721    /// detail view. Nothing is in flight there, so every panel is settled.
 722    static func webSectionData(from snapshot: LookupSnapshot, report: DomainReport) -> WebSectionViewData {
 723        WebSectionViewData(
 724            tls: SectionPanelViewData(
 725                error: snapshot.sslError,
 726                provenance: snapshot.provenanceBySection[.ssl]
 727            ),
 728            certificateRows: webCertificateRows(from: snapshot),
 729            sslInfo: snapshot.sslInfo,
 730            tlsSummary: report.web,
 731            http: SectionPanelViewData(
 732                error: snapshot.httpHeadersError,
 733                provenance: snapshot.provenanceBySection[.httpHeaders]
 734            ),
 735            responseRows: webResponseRows(from: snapshot),
 736            headers: snapshot.httpHeaders,
 737            redirect: SectionPanelViewData(
 738                error: snapshot.redirectChainError,
 739                provenance: snapshot.provenanceBySection[.redirectChain]
 740            ),
 741            redirectRows: redirectRows(from: snapshot),
 742            finalURL: snapshot.redirectChain.last?.url
 743        )
 744    }
 745
 746    static func networkSectionData(from snapshot: LookupSnapshot) -> NetworkSectionViewData {
 747        NetworkSectionViewData(
 748            reachability: SectionPanelViewData(
 749                error: snapshot.reachabilityError,
 750                provenance: snapshot.provenanceBySection[.reachability]
 751            ),
 752            reachabilityRows: reachabilityRows(from: snapshot),
 753            location: SectionPanelViewData(
 754                error: snapshot.ipGeolocationError,
 755                provenance: snapshot.provenanceBySection[.ipGeolocation],
 756                confidence: snapshot.geolocationConfidence
 757            ),
 758            locationRows: locationRows(from: snapshot),
 759            geolocation: snapshot.ipGeolocation,
 760            portScan: SectionPanelViewData(
 761                error: snapshot.portScanError,
 762                provenance: snapshot.provenanceBySection[.portScan]
 763            ),
 764            standardPortRows: portRows(from: snapshot, kind: .standard),
 765            customPortRows: portRows(from: snapshot, kind: .custom),
 766            isCloudflareProxied: snapshot.httpHeaders.contains { $0.name.lowercased() == "cf-ray" }
 767        )
 768    }
 769
 770    /// Everything the Web section draws, assembled in one place. The call
 771    /// site used to name seventeen arguments and had to keep their order
 772    /// straight; this groups them by the card they belong to (A10).
 773    var webSectionData: WebSectionViewData {
 774        WebSectionViewData(
 775            tls: SectionPanelViewData(
 776                isLoading: sslLoading || hstsLoading,
 777                error: sslError,
 778                provenance: currentSnapshot.provenanceBySection[.ssl]
 779            ),
 780            certificateRows: webCertificateRows,
 781            sslInfo: sslInfo,
 782            tlsSummary: currentTLSSummary,
 783            http: SectionPanelViewData(
 784                isLoading: httpHeadersLoading,
 785                error: httpHeadersError,
 786                provenance: currentSnapshot.provenanceBySection[.httpHeaders]
 787            ),
 788            responseRows: webResponseRows,
 789            headers: httpHeaders,
 790            redirect: SectionPanelViewData(
 791                isLoading: redirectChainLoading,
 792                error: redirectChainError,
 793                provenance: currentSnapshot.provenanceBySection[.redirectChain]
 794            ),
 795            redirectRows: redirectRows,
 796            finalURL: currentSnapshot.redirectChain.last?.url
 797        )
 798    }
 799
 800    /// Everything the Network section draws. Twenty-two arguments before.
 801    var networkSectionData: NetworkSectionViewData {
 802        NetworkSectionViewData(
 803            reachability: SectionPanelViewData(
 804                isLoading: reachabilityLoading,
 805                error: reachabilityError,
 806                provenance: currentSnapshot.provenanceBySection[.reachability]
 807            ),
 808            reachabilityRows: reachabilityRows,
 809            location: SectionPanelViewData(
 810                isLoading: ipGeolocationLoading,
 811                error: ipGeolocationError,
 812                provenance: currentSnapshot.provenanceBySection[.ipGeolocation],
 813                confidence: currentSnapshot.geolocationConfidence
 814            ),
 815            locationRows: locationRows,
 816            geolocation: ipGeolocation,
 817            portScan: SectionPanelViewData(
 818                isLoading: portScanLoading,
 819                error: portScanError,
 820                provenance: currentSnapshot.provenanceBySection[.portScan]
 821            ),
 822            standardPortRows: standardPortRows,
 823            customPortRows: customPortRows,
 824            customPortScan: SectionPanelViewData(
 825                isLoading: customPortScanLoading,
 826                error: customPortScanError
 827            ),
 828            isCloudflareProxied: isCloudflareProxied
 829        )
 830    }
 831
 832    var webCertificateRows: [InfoRowViewData] {
 833        Self.webCertificateRows(from: currentSnapshot)
 834    }
 835
 836    var webResponseRows: [InfoRowViewData] {
 837        Self.webResponseRows(from: currentSnapshot)
 838    }
 839
 840    var redirectRows: [RedirectHopViewData] {
 841        Self.redirectRows(from: currentSnapshot)
 842    }
 843
 844    var emailRows: [EmailRowViewData] {
 845        Self.emailRows(from: currentSnapshot)
 846    }
 847
 848    var ownershipRows: [InfoRowViewData] {
 849        Self.ownershipRows(from: currentSnapshot)
 850    }
 851
 852    var subdomainRows: [SubdomainRowViewData] {
 853        Self.subdomainRows(from: combinedSubdomains)
 854    }
 855
 856    var reachabilityRows: [ReachabilityRowViewData] {
 857        Self.reachabilityRows(from: currentSnapshot)
 858    }
 859
 860    var locationRows: [InfoRowViewData] {
 861        Self.locationRows(from: currentSnapshot)
 862    }
 863
 864    var standardPortRows: [PortScanRowViewData] {
 865        Self.portRows(from: currentSnapshot, kind: .standard)
 866    }
 867
 868    var customPortRows: [PortScanRowViewData] {
 869        Self.portRows(from: currentSnapshot, kind: .custom)
 870    }
 871
 872    var combinedPortScanError: String? {
 873        [portScanError, customPortScanError].compactMap { $0 }.joined(separator: "\n").nilIfEmpty
 874    }
 875
 876    @discardableResult
 877    func trackCurrentDomain() -> Bool {
 878        guard !searchedDomain.isEmpty else { return false }
 879        return trackDomain(domain: searchedDomain, availabilityStatus: availabilityResult?.status)
 880    }
 881
 882    @discardableResult
 883    func trackDomain(domain: String, availabilityStatus: DomainAvailabilityStatus?) -> Bool {
 884        let normalizedDomain = normalizedDomain(domain)
 885        guard !normalizedDomain.isEmpty else { return false }
 886
 887        if trackedDomain(for: normalizedDomain) != nil {
 888            return true
 889        }
 890
 891        guard FeatureAccessService.canAddTrackedDomain(currentCount: trackedDomains.count) else {
 892            upgradePrompt = FeatureAccessService.upgradePromptForTrackedDomains(currentCount: trackedDomains.count)
 893            return false
 894        }
 895
 896        trackedDomains.insert(
 897            TrackedDomain(
 898                domain: normalizedDomain,
 899                createdAt: Date(),
 900                updatedAt: Date(),
 901                lastKnownAvailability: availabilityStatus,
 902                collaboration: CollaborationMetadata(
 903                    scope: .privateDatabase,
 904                    ownership: .owner,
 905                    permission: .editable
 906                )
 907            ),
 908            at: 0
 909        )
 910        persistTrackedDomains()
 911        sanitizeMonitoringSelection()
 912        linkTrackedDomainHistory(for: normalizedDomain)
 913        return true
 914    }
 915
 916    func refreshTrackedDomain(_ trackedDomain: TrackedDomain) {
 917        refreshingTrackedDomainID = trackedDomain.id
 918        domain = trackedDomain.domain
 919        Task { [weak self] in
 920            guard let self else { return }
 921            self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
 922        }
 923        run()
 924    }
 925
 926    func rerunInspection(for trackedDomain: TrackedDomain) {
 927        rerunInspection(for: trackedDomain, useSnapshotResolver: false)
 928    }
 929
 930    func deleteTrackedDomains(at offsets: IndexSet) {
 931        let removedDomains = offsets.map { sortedTrackedDomains[$0] }
 932        let ids = removedDomains.map(\.id)
 933        CloudSyncService.shared.recordTrackedDomainReset(removedDomains)
 934        trackedDomains.removeAll { ids.contains($0.id) }
 935        var relinked: [HistoryEntry] = []
 936        history.indices.forEach { index in
 937            if let trackedDomainID = history[index].trackedDomainID, ids.contains(trackedDomainID) {
 938                history[index].trackedDomainID = nil
 939                relinked.append(history[index])
 940            }
 941        }
 942        persistTrackedDomains()
 943        relinked.forEach { updateStoredHistory($0) }
 944        sanitizeMonitoringSelection()
 945    }
 946
 947    func deleteTrackedDomain(_ trackedDomain: TrackedDomain) {
 948        guard canDelete(trackedDomain) else { return }
 949        CloudSyncService.shared.recordTrackedDomainDeletion(trackedDomain)
 950        trackedDomains.removeAll { $0.id == trackedDomain.id }
 951        var relinked: [HistoryEntry] = []
 952        history.indices.forEach { index in
 953            if history[index].trackedDomainID == trackedDomain.id {
 954                history[index].trackedDomainID = nil
 955                relinked.append(history[index])
 956            }
 957        }
 958        persistTrackedDomains()
 959        relinked.forEach { updateStoredHistory($0) }
 960        sanitizeMonitoringSelection()
 961    }
 962
 963    func togglePinned(for trackedDomain: TrackedDomain) {
 964        guard canEdit(trackedDomain) else { return }
 965        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 966        trackedDomains[index].isPinned.toggle()
 967        trackedDomains[index].updatedAt = Date()
 968        persistTrackedDomains()
 969    }
 970
 971    func updateNote(_ note: String, for trackedDomain: TrackedDomain) {
 972        guard canEdit(trackedDomain) else { return }
 973        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 974        trackedDomains[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
 975        trackedDomains[index].updatedAt = Date()
 976        CloudSyncService.shared.markNoteChanged(for: trackedDomains[index].domain, updatedAt: trackedDomains[index].updatedAt)
 977        persistTrackedDomains()
 978    }
 979
 980    func updateTags(_ tags: [String], for trackedDomain: TrackedDomain) {
 981        guard canEdit(trackedDomain) else { return }
 982        guard let index = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) else { return }
 983        let normalized = Self.normalizedTags(tags)
 984        trackedDomains[index].tags = normalized
 985        trackedDomains[index].updatedAt = Date()
 986        persistTrackedDomains()
 987    }
 988
 989    /// All tags currently in use across the watchlist, sorted for stable display.
 990    var allWatchlistTags: [String] {
 991        Array(Set(trackedDomains.flatMap(\.tags))).sorted()
 992    }
 993
 994    func saveCurrentWatchlistView(name: String) {
 995        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
 996        guard !trimmedName.isEmpty else { return }
 997        let view = WatchlistSavedView(
 998            name: trimmedName,
 999            tag: watchlistTagFilter,
1000            filter: watchlistFilter,
1001            sort: watchlistSortOption
1002        )
1003        watchlistSavedViews.append(view)
1004        persistWatchlistSavedViews()
1005    }
1006
1007    func applyWatchlistSavedView(_ view: WatchlistSavedView) {
1008        watchlistTagFilter = view.tag
1009        watchlistFilter = view.filter
1010        watchlistSortOption = view.sort
1011    }
1012
1013    func deleteWatchlistSavedViews(at offsets: IndexSet) {
1014        watchlistSavedViews.remove(atOffsets: offsets)
1015        persistWatchlistSavedViews()
1016    }
1017
1018    private static let watchlistSavedViewsKey = "watchlistSavedViews"
1019
1020    private static func loadWatchlistSavedViews(defaults: UserDefaults) -> [WatchlistSavedView] {
1021        guard let data = defaults.data(forKey: watchlistSavedViewsKey),
1022              let views = try? JSONDecoder().decode([WatchlistSavedView].self, from: data)
1023        else { return [] }
1024        return views
1025    }
1026
1027    private func persistWatchlistSavedViews() {
1028        guard let data = try? JSONEncoder().encode(watchlistSavedViews) else { return }
1029        defaults.set(data, forKey: Self.watchlistSavedViewsKey)
1030    }
1031
1032    private static func normalizedTags(_ tags: [String]) -> [String] {
1033        var seen = Set<String>()
1034        var normalized: [String] = []
1035        for tag in tags {
1036            let trimmed = tag.trimmingCharacters(in: .whitespacesAndNewlines)
1037            guard !trimmed.isEmpty, seen.insert(trimmed.lowercased()).inserted else { continue }
1038            normalized.append(trimmed)
1039        }
1040        return normalized.sorted()
1041    }
1042
1043    func removeHistoryEntries(at offsets: IndexSet) {
1044        let removed = Set(offsets.map { history[$0].id })
1045        history.remove(atOffsets: offsets)
1046        removeStoredHistory(ids: removed)
1047    }
1048
1049    func removeHistoryEntries(withIDs ids: [UUID]) {
1050        history.removeAll { ids.contains($0.id) }
1051        removeStoredHistory(ids: Set(ids))
1052    }
1053
1054    func clearHistory() {
1055        history.removeAll()
1056        DomainDataPortabilityService.removeAllHistoryEntries(
1057            defaults: defaults,
1058            historyLocation: historyLocation
1059        )
1060        refreshDataLifecycleSummary()
1061        clearMonitoringLogs()
1062        refreshDataLifecycleSummary()
1063    }
1064
1065    func clearLookupCache() {
1066        Task {
1067            await LookupRuntime.shared.clearCache()
1068        }
1069    }
1070
1071    func clearWorkflows() {
1072        CloudSyncService.shared.recordWorkflowReset(workflows)
1073        workflows.removeAll()
1074        latestWorkflowRunSummary = nil
1075        persistWorkflows()
1076        refreshDataLifecycleSummary()
1077    }
1078
1079    func clearTrackedDomains() {
1080        CloudSyncService.shared.recordTrackedDomainReset(trackedDomains)
1081        trackedDomains.removeAll()
1082        refreshingTrackedDomainID = nil
1083        persistTrackedDomains()
1084        sanitizeMonitoringSelection()
1085        clearMonitoringLogs()
1086        refreshDataLifecycleSummary()
1087    }
1088
1089    func clearRecentSearches() {
1090        recentSearches.removeAll()
1091        DomainDataPortabilityService.saveRecentSearches([], defaults: defaults)
1092        CloudSyncService.shared.markAppSettingsChanged()
1093        refreshDataLifecycleSummary()
1094    }
1095
1096    func refreshMonitoringState() {
1097        #if DEBUG
1098        // Runs right after fixture seeding in the app task (and again on every
1099        // scene activation); the disk reload below would wipe the fixtures.
1100        if auditFixturesActive { return }
1101        #endif
1102        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
1103        trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1104        history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
1105        monitoringSettings = MonitoringStorage.sanitizeSettings(
1106            MonitoringStorage.loadSettings(defaults: defaults),
1107            trackedDomains: trackedDomains
1108        )
1109        monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
1110        persistMonitoringSettings()
1111        refreshDataLifecycleSummary()
1112    }
1113
1114    func refreshDataLifecycleSummary() {
1115        dataLifecycleSummary = DomainDataPortabilityService.lifecycleSummary(defaults: defaults, historyLocation: historyLocation)
1116    }
1117
1118    func refreshPersistedData() {
1119        #if DEBUG
1120        // A reload from disk would silently replace the in-memory fixtures.
1121        if auditFixturesActive { return }
1122        #endif
1123        recentSearches = DomainDataPortabilityService.loadRecentSearches(defaults: defaults)
1124        trackedDomains = Self.loadTrackedDomains(defaults: defaults, historyLocation: historyLocation)
1125        history = Self.loadHistoryEntries(defaults: defaults, historyLocation: historyLocation)
1126        auditSessions = DomainDataPortabilityService.loadAuditSessions(defaults: defaults)
1127        workflows = Self.loadWorkflows(defaults: defaults, historyLocation: historyLocation)
1128        monitoringSettings = MonitoringStorage.sanitizeSettings(
1129            MonitoringStorage.loadSettings(defaults: defaults),
1130            trackedDomains: trackedDomains
1131        )
1132        monitoringLogs = MonitoringStorage.loadLogs(defaults: defaults)
1133        refreshDataLifecycleSummary()
1134    }
1135
1136    func applyLocalDataReset() async {
1137        domain = ""
1138        bulkInput = ""
1139        reset()
1140
1141        recentSearches = []
1142        trackedDomains = []
1143        history = []
1144        auditSessions = []
1145        workflows = []
1146        historySearchText = ""
1147        historyDateFilter = .all
1148        historyChangeFilter = .all
1149        historySortOption = .newest
1150        timelineGrouping = .relativeDay
1151        timelineDomainFilter = ""
1152        watchlistSearchText = ""
1153        watchlistFilter = .all
1154        watchlistSortOption = .pinned
1155        dashboardSearchText = ""
1156        dashboardFilter = .all
1157        monitoringSettings = MonitoringSettings()
1158        monitoringLogs = []
1159        notificationsAuthorized = false
1160        monitoringRunInProgress = false
1161        monitoringStatusMessage = nil
1162        portabilityStatusMessage = "All local data removed."
1163        upgradePrompt = nil
1164        isPaywallPresented = false
1165        selectedSnapshotIDs.removeAll()
1166        activeDomainDiff = nil
1167        activeDiffChangeIndex = 0
1168        latestBatchSweepSummary = nil
1169        latestWorkflowRunSummary = nil
1170        historyAutoPruneOption = Self.loadHistoryAutoPruneOption(defaults: defaults)
1171        refreshDataLifecycleSummary()
1172        await refreshMonitoringAuthorizationStatus()
1173    }
1174
1175    func rerunLookup(from entry: HistoryEntry, useSnapshotResolver: Bool) {
1176        if useSnapshotResolver {
1177            defaults.set(entry.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
1178        }
1179        domain = entry.domain
1180        run()
1181        rerunNavigationToken = UUID()
1182    }
1183
1184    func rerunInspection(for trackedDomain: TrackedDomain, useSnapshotResolver: Bool) {
1185        if useSnapshotResolver, let snapshot = latestSnapshot(for: trackedDomain) {
1186            defaults.set(snapshot.resolverURLString, forKey: DNSResolverOption.userDefaultsKey)
1187        }
1188        domain = trackedDomain.domain
1189        run()
1190        rerunNavigationToken = UUID()
1191    }
1192
1193    func openInspection(for domain: String) {
1194        self.domain = normalizedDomain(domain)
1195        run()
1196        rerunNavigationToken = UUID()
1197    }
1198
1199    func reset() {
1200        lookupTask?.cancel()
1201        customPortScanTask?.cancel()
1202        batchTask?.cancel()
1203        hasRun = false
1204        searchedDomain = ""
1205        lastLookupDurationMs = nil
1206        currentDiffSections = []
1207        currentChangeSummary = nil
1208        ownershipDiff = []
1209        currentReport = nil
1210        refreshingTrackedDomainID = nil
1211        clearBatchState()
1212        clearLookupState()
1213    }
1214
1215    func clearPresentedResults() {
1216        reset()
1217    }
1218
1219    func run() {
1220        let target: String
1221        switch DomainName.validate(trimmedDomain) {
1222        case .success(let host):
1223            target = host
1224            domainInputError = nil
1225        case .failure(let error):
1226            domainInputError = error.localizedDescription
1227            return
1228        }
1229
1230        clearBatchState()
1231        let lookupID = beginLookup(for: target)
1232
1233        lookupTask = Task { [weak self] in
1234            guard let self else { return }
1235            _ = await self.performLookup(domain: target, lookupID: lookupID)
1236        }
1237    }
1238
1239    func runBulkLookup() {
1240        let parsed = parsedBulkInput(from: bulkInput)
1241        bulkInputError = parsed.skippedMessage
1242
1243        guard !parsed.domains.isEmpty else { return }
1244        guard FeatureAccessService.canRunBatch(domainCount: parsed.domains.count) else {
1245            upgradePrompt = FeatureAccessService.upgradePromptForBatch(domainCount: parsed.domains.count)
1246            return
1247        }
1248        startBatchLookup(domains: parsed.domains, source: .manual)
1249    }
1250
1251    func refreshAllTrackedDomains() {
1252        guard FeatureAccessService.canRunBatch(domainCount: sortedTrackedDomains.count) else {
1253            upgradePrompt = FeatureAccessService.upgradePromptForBatch(domainCount: sortedTrackedDomains.count)
1254            return
1255        }
1256        startBatchLookup(domains: sortedTrackedDomains.map(\.domain), source: .watchlistRefresh)
1257    }
1258
1259    func cancelBatchLookup() {
1260        batchTask?.cancel()
1261        batchLookupRunning = false
1262        batchCurrentDomain = nil
1263        activeBatchDomains = []
1264        refreshingTrackedDomainID = nil
1265
1266        for index in batchResults.indices where batchResults[index].status == .pending || batchResults[index].status == .running {
1267            batchResults[index] = BatchLookupResult(
1268                id: batchResults[index].id,
1269                domain: batchResults[index].domain,
1270                historyEntryID: batchResults[index].historyEntryID,
1271                availability: batchResults[index].availability,
1272                primaryIP: batchResults[index].primaryIP,
1273                quickStatus: "Cancelled",
1274                summaryMessage: batchResults[index].summaryMessage,
1275                changeSeverity: batchResults[index].changeSeverity,
1276                changeClassification: batchResults[index].changeClassification,
1277                certificateWarningLevel: batchResults[index].certificateWarningLevel,
1278                riskScore: batchResults[index].riskScore,
1279                riskLevel: batchResults[index].riskLevel,
1280                timestamp: Date(),
1281                status: .failed,
1282                errorMessage: "Lookup cancelled"
1283            )
1284        }
1285    }
1286
1287    func canEdit(_ trackedDomain: TrackedDomain) -> Bool {
1288        trackedDomain.collaboration?.canEdit ?? true
1289    }
1290
1291    func canDelete(_ trackedDomain: TrackedDomain) -> Bool {
1292        trackedDomain.collaboration?.isOwner ?? true
1293    }
1294
1295    func collaborationLabel(for trackedDomain: TrackedDomain) -> String? {
1296        guard let collaboration = trackedDomain.collaboration, collaboration.isShared else { return nil }
1297        return "\(collaboration.ownership.title) • \(collaboration.permission.title)"
1298    }
1299
1300    func runCustomPortScan(ports: [UInt16]) async {
1301        guard !searchedDomain.isEmpty else {
1302            customPortScanState = .settled(value: [], error: "Run a domain lookup first")
1303            return
1304        }
1305
1306        guard !ports.isEmpty else {
1307            customPortScanState = .settled(value: [], error: "Enter at least one valid port")
1308            return
1309        }
1310
1311        customPortScanTask?.cancel()
1312        let domain = searchedDomain
1313        let lookupID = activeLookupID
1314
1315        customPortScanState = .loading
1316
1317        customPortScanTask = Task { [weak self] in
1318            guard let self else { return }
1319            let result = await PortScanService.scanPorts(domain: domain, ports: ports, timeout: 3.0)
1320            guard !Task.isCancelled, self.isCurrentLookup(lookupID) else { return }
1321            self.applyCustomPortResult(result)
1322        }
1323    }
1324
1325    @discardableResult
1326    func startAudit(for domain: String, reviewer: String? = nil) async -> AuditSession? {
1327        let normalizedDomain = domain
1328            .trimmingCharacters(in: .whitespacesAndNewlines)
1329            .replacingOccurrences(of: "https://", with: "")
1330            .replacingOccurrences(of: "http://", with: "")
1331            .components(separatedBy: "/").first?
1332            .lowercased() ?? domain.lowercased()
1333        guard !normalizedDomain.isEmpty else { return nil }
1334
1335        // Free keeps one audit open at a time so the feature stays discoverable;
1336        // finishing one frees the slot. Existing sessions are never closed off.
1337        if let limit = FeatureAccessService.entitlements.activeAuditSessionLimit,
1338           auditSessions.filter({ $0.status != .complete }).count >= limit {
1339            upgradePrompt = FeatureAccessService.upgradePrompt(for: .auditDepth)
1340            return nil
1341        }
1342
1343        let previous = historyEntries(for: normalizedDomain).first?.snapshot
1344        let snapshot = await inspectionService.inspectSnapshot(
1345            domain: normalizedDomain,
1346            previousSnapshot: previous,
1347            scope: InspectionScope.current(defaults: defaults)
1348        )
1349        guard let entry = saveHistoryEntry(
1350            from: snapshot,
1351            replaceLatest: false,
1352            updateCurrentState: searchedDomain.caseInsensitiveCompare(normalizedDomain) == .orderedSame
1353        ) else {
1354            return nil
1355        }
1356
1357        let report = report(for: entry)
1358        let historicalContext = Array(historyEntries(for: normalizedDomain).dropFirst().prefix(6)).map(\.snapshotSummary)
1359        let screenshots = snapshotEvidenceAssets(from: report)
1360        let session = AuditSession(
1361            domain: normalizedDomain,
1362            createdAt: entry.timestamp,
1363            reviewer: (reviewer?.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty) ?? Self.defaultAuditReviewer,
1364            status: .draft,
1365            evidence: AuditEvidenceSnapshot(
1366                capturedAt: entry.timestamp,
1367                lookup: entry,
1368                report: report,
1369                historicalContext: historicalContext,
1370                screenshots: screenshots
1371            ),
1372            findings: [],
1373            notes: "",
1374            checklist: AuditChecklistArea.defaultItems
1375        )
1376
1377        auditSessions.insert(session, at: 0)
1378        persistAuditSessions()
1379        return session
1380    }
1381
1382    func loadOwnershipHistory() async {
1383        await loadLookup(into: \.ownershipHistoryState, fallback: "Ownership history unavailable") {
1384            await ExternalDataService.shared.ownershipHistory(
1385                domain: searchedDomain,
1386                currentOwnership: ownershipResult,
1387                historyEntries: history
1388            ).value
1389        }
1390    }
1391
1392    func loadDNSHistory() async {
1393        await loadLookup(into: \.dnsHistoryState, fallback: "DNS history unavailable") {
1394            await ExternalDataService.shared.dnsHistory(
1395                domain: searchedDomain,
1396                dnsSections: dnsSections,
1397                historyEntries: history
1398            ).value
1399        }
1400    }
1401
1402    func loadExtendedSubdomains() async {
1403        await loadLookup(
1404            .extendedSubdomains,
1405            into: \.extendedSubdomainsState,
1406            fallback: "Extended subdomains unavailable"
1407        ) {
1408            await ExternalDataService.shared.extendedSubdomains(
1409                domain: searchedDomain,
1410                existing: subdomains
1411            ).value
1412        }
1413    }
1414
1415    /// Loads a lookup for the searched domain into `items`, unless it is loaded
1416    /// already. With a `capability`, shows the upgrade prompt when the plan
1417    /// doesn't include it; without one the lookup is open to every tier.
1418    private func loadLookup<Item>(
1419        _ capability: FeatureCapability? = nil,
1420        into state: ReferenceWritableKeyPath<DomainViewModel, SectionState<[Item]>>,
1421        fallback: String,
1422        fetch: () async -> ServiceResult<[Item]>
1423    ) async {
1424        guard !searchedDomain.isEmpty else { return }
1425        if let capability, !FeatureAccessService.hasAccess(to: capability) {
1426            upgradePrompt = FeatureAccessService.upgradePrompt(for: capability)
1427            return
1428        }
1429        guard self[keyPath: state].items.isEmpty else { return }
1430
1431        self[keyPath: state] = .loading
1432        let (items, message) = found(await fetch(), fallback: fallback)
1433        self[keyPath: state] = .settled(value: items, error: message)
1434        _ = saveHistoryEntry(replaceLatest: true)
1435    }
1436
1437    /// What a lookup found, and the message to show when it found nothing or failed.
1438    private func found<Item>(_ result: ServiceResult<[Item]>, fallback: String) -> ([Item], String?) {
1439        switch result {
1440        case let .success(items):
1441            return (items, nil)
1442        case let .empty(message):
1443            return ([], message)
1444        case let .error(message):
1445            return ([], conciseExternalMessage(message, fallback: fallback))
1446        }
1447    }
1448
1449    private func performLookup(domain: String, lookupID: UUID) async -> HistoryEntry? {
1450        let lookupStartedAt = DomainDebugLog.signpostStart("DomainViewModel.performLookup", domain: domain)
1451        let previous = previousSnapshot(
1452            for: domain,
1453            trackedDomainID: currentTrackedDomain?.id,
1454            replacingLatest: false
1455        )
1456        let inspectedSnapshot = await inspectionService.inspectSnapshot(
1457            domain: domain,
1458            previousSnapshot: previous,
1459            scope: InspectionScope.current(defaults: defaults)
1460        )
1461        DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
1462        guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
1463
1464        let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previous)
1465        let applyStartedAt = DomainDebugLog.signpostStart("DomainViewModel.applySnapshot", domain: domain)
1466        applySnapshot(snapshot)
1467        DomainDebugLog.signpostEnd("DomainViewModel.applySnapshot", start: applyStartedAt, domain: domain)
1468        lastLookupDurationMs = snapshot.totalLookupDurationMs
1469        refreshingTrackedDomainID = nil
1470
1471        guard snapshot.statusMessage == nil else {
1472            return history.first(where: { $0.id == snapshot.historyEntryID })
1473        }
1474
1475        let saveStartedAt = DomainDebugLog.signpostStart("DomainViewModel.saveHistoryEntry", domain: domain)
1476        let entry = saveHistoryEntry(replaceLatest: false, reuseCurrentAnalysis: true)
1477        DomainDebugLog.signpostEnd("DomainViewModel.saveHistoryEntry", start: saveStartedAt, domain: domain)
1478        // Opt-in, and off by default: this fires on every Run, so a target
1479        // that enabled it ships an object per tap.
1480        IntegrationService.shared.enqueueExports(domains: [domain], trigger: .interactiveRun)
1481        DomainDebugLog.signpostEnd("DomainViewModel.performLookup", start: lookupStartedAt, domain: domain)
1482        return entry
1483    }
1484
1485    /// The single place section state is written from an inspection result.
1486    /// Internal so the tests that pin what each section ends up showing can
1487    /// reach it without a live lookup.
1488    func applySnapshot(_ snapshot: LookupSnapshot) {
1489        currentInspectionMetadata = InspectionMetadata(snapshot: snapshot)
1490        currentHistoryEntryID = snapshot.historyEntryID
1491        currentSnapshotTimestamp = snapshot.timestamp
1492        currentResultSource = snapshot.resultSource
1493        currentCachedSections = snapshot.cachedSections
1494        currentStatusMessage = snapshot.statusMessage
1495        currentDiffSections = []
1496        ownershipDiff = []
1497        let reportStartedAt = DomainDebugLog.signpostStart("DomainViewModel.reportBuilder.build", domain: snapshot.domain)
1498        currentReport = reportBuilder.build(
1499            from: snapshot,
1500            previousSnapshot: previousSnapshot(
1501                for: snapshot.domain,
1502                trackedDomainID: snapshot.trackedDomainID ?? trackedDomain(for: snapshot.domain)?.id,
1503                replacingLatest: false
1504            ),
1505            historyEntries: historyEntries(for: snapshot.domain)
1506        )
1507        DomainDebugLog.signpostEnd("DomainViewModel.reportBuilder.build", start: reportStartedAt, domain: snapshot.domain)
1508        currentChangeSummary = currentReport?.changeSummary ?? snapshot.changeSummary
1509
1510        dnsState = .settled(value: snapshot.dnsSections, error: snapshot.dnsError)
1511        availabilityState = .settled(value: snapshot.availabilityResult)
1512        suggestionsState = .settled(value: snapshot.suggestions)
1513        sslState = .settled(value: snapshot.sslInfo, error: snapshot.sslError)
1514        hstsState = .settled(value: snapshot.hstsPreloaded)
1515        httpHeadersState = .settled(value: snapshot.httpHeaders, error: snapshot.httpHeadersError)
1516        httpSecurityGrade = snapshot.httpSecurityGrade
1517        httpStatusCode = snapshot.httpStatusCode
1518        httpResponseTimeMs = snapshot.httpResponseTimeMs
1519        httpProtocol = snapshot.httpProtocol
1520        http3Advertised = snapshot.http3Advertised
1521        reachabilityState = .settled(value: snapshot.reachabilityResults, error: snapshot.reachabilityError)
1522        ipGeolocationState = .settled(value: snapshot.ipGeolocation, error: snapshot.ipGeolocationError)
1523        emailSecurityState = .settled(value: snapshot.emailSecurity, error: snapshot.emailSecurityError)
1524        ownershipState = .settled(value: snapshot.ownership, error: snapshot.ownershipError)
1525        ownershipHistoryState = .settled(value: snapshot.ownershipHistory, error: snapshot.ownershipHistoryError)
1526        ptrState = .settled(value: snapshot.ptrRecord, error: snapshot.ptrError)
1527        redirectChainState = .settled(value: snapshot.redirectChain, error: snapshot.redirectChainError)
1528        subdomainsState = .settled(value: snapshot.subdomains, error: snapshot.subdomainsError)
1529        extendedSubdomainsState = .settled(value: snapshot.extendedSubdomains, error: snapshot.extendedSubdomainsError)
1530        dnsHistoryState = .settled(value: snapshot.dnsHistory, error: snapshot.dnsHistoryError)
1531        domainPricingState = .settled(value: snapshot.domainPricing, error: snapshot.domainPricingError)
1532        reputationState = .settled(value: snapshot.reputation, error: snapshot.reputationError)
1533        portScanState = .settled(
1534            value: snapshot.portScanResults.filter { $0.kind == .standard },
1535            error: snapshot.portScanError
1536        )
1537        customPortScanState = .settled(value: snapshot.portScanResults.filter { $0.kind == .custom })
1538    }
1539
1540    private func applyCustomPortResult(_ result: ServiceResult<[PortScanResult]>) {
1541        switch result {
1542        case let .success(results):
1543            customPortScanState = .settled(value: results)
1544            _ = saveHistoryEntry(replaceLatest: true)
1545        case let .empty(message), let .error(message):
1546            customPortScanState = .settled(value: [], error: message)
1547        }
1548    }
1549
1550    private static func performBatchLookup(
1551        domain: String,
1552        previousSnapshot: LookupSnapshot?,
1553        scope: InspectionScope
1554    ) async -> BatchLookupPayload? {
1555        guard !Task.isCancelled else { return nil }
1556        let inspectionService = DomainInspectionService()
1557        let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
1558        guard !Task.isCancelled else { return nil }
1559        return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
1560    }
1561
1562    @discardableResult
1563    private func saveHistoryEntry(replaceLatest: Bool, reuseCurrentAnalysis: Bool = false) -> HistoryEntry? {
1564        guard !searchedDomain.isEmpty else { return nil }
1565        return saveHistoryEntry(
1566            from: currentSnapshot,
1567            replaceLatest: replaceLatest,
1568            updateCurrentState: true,
1569            reuseCurrentAnalysis: reuseCurrentAnalysis
1570        )
1571    }
1572
1573    @discardableResult
1574    private func saveHistoryEntry(
1575        from snapshot: LookupSnapshot,
1576        replaceLatest: Bool,
1577        updateCurrentState: Bool,
1578        reuseCurrentAnalysis: Bool = false
1579    ) -> HistoryEntry? {
1580        let trackedDomainID = snapshot.trackedDomainID ?? trackedDomain(for: snapshot.domain)?.id
1581        let previousSnapshot = previousSnapshot(for: snapshot.domain, trackedDomainID: trackedDomainID, replacingLatest: replaceLatest)
1582        let domainHistoryEntries = history.filter {
1583            $0.domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame
1584        }
1585        let analysis = reuseCurrentAnalysis ? nil : DomainInsightEngine.analyze(snapshot: snapshot, previousSnapshot: previousSnapshot)
1586        let intelligence = DomainIntelligenceService.derive(
1587            snapshot: snapshot,
1588            previousSnapshot: previousSnapshot,
1589            historyEntries: domainHistoryEntries
1590        )
1591        let changeSummary = reuseCurrentAnalysis
1592            ? currentChangeSummary ?? snapshot.changeSummary
1593            : previousSnapshot.map {
1594                DiffService.summary(
1595                    from: $0,
1596                    to: snapshot,
1597                    generatedAt: snapshot.timestamp,
1598                    riskAssessment: analysis?.riskAssessment,
1599                    insights: analysis?.insights
1600                )
1601            }
1602        let domainDiff = reuseCurrentAnalysis
1603            ? previousSnapshot.map {
1604                DomainDiff(
1605                    domain: snapshot.domain,
1606                    fromTimestamp: $0.timestamp,
1607                    toTimestamp: snapshot.timestamp,
1608                    sections: currentDiffSections,
1609                    changedSectionIDs: currentDiffSections.filter(\.hasChanges).map(\.id),
1610                    changedSectionTitles: currentDiffSections.filter(\.hasChanges).map(\.title),
1611                    contextNote: currentChangeSummary?.contextNote
1612                )
1613            }
1614            : previousSnapshot.map { DiffService.compare(from: $0, to: snapshot) }
1615        let diffSections = domainDiff?.sections ?? currentDiffSections
1616        let previousSnapshotID = previousSnapshot?.historyEntryID
1617        let nextSnapshotIndex = nextSnapshotIndex(for: snapshot.domain, trackedDomainID: trackedDomainID)
1618
1619        if updateCurrentState {
1620            currentChangeSummary = changeSummary
1621            currentDiffSections = diffSections
1622            ownershipDiff = diffSections.first(where: { $0.title == "Ownership" })?.items.filter(\.hasChanges) ?? []
1623            if !reuseCurrentAnalysis {
1624                currentReport = reportBuilder.build(
1625                    from: snapshot,
1626                    previousSnapshot: previousSnapshot,
1627                    historyEntries: domainHistoryEntries
1628                )
1629            }
1630        }
1631
1632        let entry = HistoryEntry(
1633            identity: HistoryEntry.Identity(
1634                domain: snapshot.domain,
1635                timestamp: snapshot.timestamp,
1636                trackedDomainID: trackedDomainID,
1637                note: currentHistoryEntry?.note
1638            ),
1639            inspection: .init(snapshot: snapshot),
1640            registration: HistoryEntry.Registration(
1641                ownership: snapshot.ownership,
1642                ownershipHistory: snapshot.ownershipHistory,
1643                inferredProvider: intelligence.inferredProvider,
1644                priorProviders: intelligence.priorProviders,
1645                domainClassification: intelligence.domainClassification,
1646                ownershipTransitions: intelligence.ownershipTransitions,
1647                hostingTransitions: intelligence.hostingTransitions,
1648                domainPricing: snapshot.domainPricing
1649            ),
1650            intelligence: HistoryEntry.Intelligence(
1651                subdomainHistory: intelligence.subdomainHistory,
1652                riskSignals: intelligence.riskSignals,
1653                intelligenceTimeline: intelligence.timelineEvents,
1654                reputation: snapshot.reputation
1655            ),
1656            provenance: .init(snapshot: snapshot),
1657            summary: HistoryEntry.Summary(
1658                primaryIP: Self.primaryIPAddress(from: snapshot),
1659                finalRedirectURL: Self.finalRedirectTarget(from: snapshot),
1660                tlsStatusSummary: Self.httpsSummary(from: snapshot),
1661                emailSecuritySummary: Self.emailSummary(from: snapshot),
1662                httpGradeSummary: snapshot.httpSecurityGrade ?? snapshot.httpHeadersError,
1663                changeSummary: changeSummary,
1664                snapshotIndex: nextSnapshotIndex,
1665                previousSnapshotID: previousSnapshotID,
1666                changeCount: domainDiff?.changeCount ?? changeSummary?.changedSections.count ?? 0,
1667                severitySummary: changeSummary?.severity
1668            ),
1669            failures: .init(snapshot: snapshot)
1670        )
1671
1672        if updateCurrentState {
1673            currentHistoryEntryID = entry.id
1674        }
1675
1676        // Before the insert: afterwards `history.count` includes this entry
1677        // and `growthHistoryLimit` would never prune anything.
1678        let storedLimit = growthHistoryLimit
1679        let replacedLatest = replaceLatest
1680            && !history.isEmpty
1681            && history[0].domain.caseInsensitiveCompare(snapshot.domain) == .orderedSame
1682        if replacedLatest {
1683            history[0] = entry
1684        } else {
1685            history.insert(entry, at: 0)
1686            history = Array(history.prefix(storedLimit))
1687        }
1688
1689        updateTrackedDomainSnapshotMetadata(
1690            domain: snapshot.domain,
1691            snapshotID: entry.id,
1692            availabilityStatus: snapshot.availabilityResult?.status,
1693            updatedAt: snapshot.timestamp,
1694            changeSummary: changeSummary,
1695            changeSeverity: changeSummary?.severity,
1696            certificateWarningLevel: DomainDiffService.certificateWarningLevel(for: snapshot),
1697            certificateDaysRemaining: snapshot.sslInfo?.daysUntilExpiry
1698        )
1699        if replacedLatest {
1700            updateStoredHistory(entry)
1701        } else {
1702            appendStoredHistory(entry, cap: storedLimit)
1703        }
1704        notifyIfNeeded(for: entry, snapshot: snapshot, previousSnapshot: previousSnapshot)
1705        return entry
1706    }
1707
1708    /// A single snapshot written on its own. `persistHistory` rewrites every
1709    /// row because it cannot tell what changed; these callers can, and at the
1710    /// Pro+ cap that is the difference between 23 ms and 656 ms.
1711    /// Replaces one stored snapshot. No cap: an update changes a row that is
1712    /// already there and cannot push the store past its limit.
1713    private func updateStoredHistory(_ entry: HistoryEntry) {
1714        if historyPersistenceSuspended {
1715            historyPersistenceDirty = true
1716            return
1717        }
1718        DomainDataPortabilityService.updateHistoryEntry(
1719            entry,
1720            defaults: defaults,
1721            historyLocation: historyLocation
1722        )
1723        refreshDataLifecycleSummary()
1724    }
1725
1726    /// Stores a new snapshot under `cap`, which the caller reads before its
1727    /// own insert so the row being added does not raise its own ceiling.
1728    private func appendStoredHistory(_ entry: HistoryEntry, cap: Int) {
1729        if historyPersistenceSuspended {
1730            historyPersistenceDirty = true
1731            return
1732        }
1733        DomainDataPortabilityService.appendHistoryEntry(
1734            entry,
1735            cap: cap,
1736            defaults: defaults,
1737            historyLocation: historyLocation
1738        )
1739        refreshDataLifecycleSummary()
1740    }
1741
1742    private func removeStoredHistory(ids: Set<UUID>) {
1743        if historyPersistenceSuspended {
1744            historyPersistenceDirty = true
1745            return
1746        }
1747        DomainDataPortabilityService.removeHistoryEntries(
1748            ids: ids,
1749            defaults: defaults,
1750            historyLocation: historyLocation
1751        )
1752        refreshDataLifecycleSummary()
1753    }
1754
1755    /// Rewrites the whole store. Only the auto-prune setting needs this — it
1756    /// drops rows from the middle and cannot say which. Every other writer
1757    /// goes through `appendStoredHistory`, `updateStoredHistory` or
1758    /// `removeStoredHistory`.
1759    private func persistHistory() {
1760        if historyPersistenceSuspended {
1761            historyPersistenceDirty = true
1762            return
1763        }
1764        let persistStartedAt = DomainDebugLog.signpostStart("DomainViewModel.persistHistory")
1765        DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1766        refreshDataLifecycleSummary()
1767        DomainDebugLog.signpostEnd("DomainViewModel.persistHistory", start: persistStartedAt, extra: "count=\(history.count)")
1768    }
1769
1770    func persistAuditSessions() {
1771        DomainDataPortabilityService.saveAuditSessions(auditSessions, defaults: defaults)
1772        refreshDataLifecycleSummary()
1773    }
1774
1775    func setHistoryAutoPruneOption(_ option: HistoryAutoPruneOption) {
1776        historyAutoPruneOption = option
1777        defaults.set(option.rawValue, forKey: Self.historyAutoPruneKey)
1778        history = Array(history.prefix(requestedHistoryLimit))
1779        persistHistory()
1780    }
1781
1782    func updateHistoryNote(_ note: String, for entry: HistoryEntry) {
1783        guard let index = history.firstIndex(where: { $0.id == entry.id }) else { return }
1784        history[index].note = note.trimmingCharacters(in: .whitespacesAndNewlines).nilIfEmpty
1785        updateStoredHistory(history[index])
1786    }
1787
1788    #if DEBUG
1789    /// True when this session was launched with `DOMAIN_DIG_SEED_FIXTURES`.
1790    /// Blocks tracked-domain persistence, widget-store writes, and persisted-data
1791    /// reloads so fixture data stays strictly in-memory — the audit suite relies
1792    /// on every launch starting from the same state.
1793    private(set) var auditFixturesActive = false
1794
1795    func seedAuditFixturesIfRequested() {
1796        // Independent of the fixtures below: Inspect renders either a result or
1797        // the recent list, so the two cannot be seeded together.
1798        if AuditFixtures.recentSearchesRequested {
1799            recentSearches = AuditFixtures.recentSearches
1800        }
1801        guard AuditFixtures.requested, !auditFixturesActive else { return }
1802        auditFixturesActive = true
1803        trackedDomains = AuditFixtures.trackedDomains
1804        batchResults = AuditFixtures.batchResults
1805    }
1806    #endif
1807
1808    private func persistTrackedDomains() {
1809        #if DEBUG
1810        if auditFixturesActive { return }
1811        #endif
1812        if trackedDomainsPersistenceSuspended {
1813            trackedDomainsPersistenceDirty = true
1814            return
1815        }
1816        DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
1817        CloudSyncService.shared.scheduleSyncIfNeeded()
1818        refreshDataLifecycleSummary()
1819        refreshWidgetData()
1820    }
1821
1822    private func beginBulkPersistenceDeferral() {
1823        historyPersistenceSuspended = true
1824        trackedDomainsPersistenceSuspended = true
1825        historyPersistenceDirty = false
1826        trackedDomainsPersistenceDirty = false
1827    }
1828
1829    private func endBulkPersistenceDeferral() {
1830        historyPersistenceSuspended = false
1831        trackedDomainsPersistenceSuspended = false
1832
1833        if trackedDomainsPersistenceDirty {
1834            trackedDomainsPersistenceDirty = false
1835            DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
1836            CloudSyncService.shared.scheduleSyncIfNeeded()
1837        }
1838
1839        if historyPersistenceDirty {
1840            historyPersistenceDirty = false
1841            DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1842        }
1843
1844        refreshDataLifecycleSummary()
1845    }
1846
1847    /// What Settings says under the auto-prune picker. The old copy claimed
1848    /// auto-prune "defaults to unlimited", which was never true — there has
1849    /// always been a hard ceiling, and under D1 it is the tier's.
1850    var historyRetentionCaption: String {
1851        let limit = tierHistoryLimit
1852        let base = "History stays on this device. Your plan keeps up to \(limit) snapshots"
1853        guard history.count > limit else {
1854            return base + "; auto-prune trims to fewer if you want."
1855        }
1856        return base
1857            + ", and you have \(history.count). Nothing already saved is removed —"
1858            + " new snapshots replace the oldest instead."
1859    }
1860
1861    /// Snapshots this tier keeps: 50 free, 250 Pro, 2000 Pro+ under D1.
1862    private var tierHistoryLimit: Int {
1863        FeatureAccessService.historyRetentionLimit
1864    }
1865
1866    /// The ceiling a newly stored snapshot is kept under, computed before the
1867    /// insert. Never below what is already held: a lapsed Pro+ subscriber with
1868    /// 2000 snapshots keeps all 2000 (Review Focus #6), and the store holds
1869    /// there rather than draining to the lower tier a row at a time. For
1870    /// anyone at or under their tier's limit this is just that limit.
1871    var growthHistoryLimit: Int {
1872        max(tierHistoryLimit, history.count)
1873    }
1874
1875    /// What the user's own auto-prune choice asks for, which may be less than
1876    /// the tier allows but never more. This one is permitted to delete,
1877    /// because the user chose it.
1878    var requestedHistoryLimit: Int {
1879        min(historyAutoPruneOption.keepCount ?? tierHistoryLimit, tierHistoryLimit)
1880    }
1881
1882    /// Caps growth without pruning what is already stored.
1883    private func trimHistoryToLimit() {
1884        history = Array(history.prefix(growthHistoryLimit))
1885    }
1886
1887    private func nextSnapshotIndex(for domain: String, trackedDomainID: UUID?) -> Int {
1888        let siblings = history.filter { entry in
1889            if let trackedDomainID {
1890                return entry.trackedDomainID == trackedDomainID
1891            }
1892            return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1893        }
1894        let existingMax = siblings.compactMap(\.snapshotIndex).max() ?? siblings.count
1895        return existingMax + 1
1896    }
1897
1898    func persistMonitoringSettings(localActivationConfirmed: Bool = false) {
1899        monitoringSettings = MonitoringStorage.sanitizeSettings(monitoringSettings, trackedDomains: trackedDomains)
1900        MonitoringStorage.saveSettings(monitoringSettings, defaults: defaults)
1901        CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: localActivationConfirmed)
1902    }
1903
1904    func sanitizeMonitoringSelection() {
1905        monitoringSettings = MonitoringStorage.sanitizeSettings(monitoringSettings, trackedDomains: trackedDomains)
1906        MonitoringStorage.saveSettings(monitoringSettings, defaults: defaults)
1907        CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: false)
1908    }
1909
1910    private func clearMonitoringLogs() {
1911        monitoringLogs.removeAll()
1912        monitoringStatusMessage = nil
1913        MonitoringStorage.saveLogs([], defaults: defaults)
1914    }
1915
1916    private func updateTrackedDomainAvailability(for domain: String, status: DomainAvailabilityStatus) {
1917        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1918            return
1919        }
1920        trackedDomains[index].lastKnownAvailability = status
1921        persistTrackedDomains()
1922    }
1923
1924    private func updateTrackedDomainSnapshotMetadata(
1925        domain: String,
1926        snapshotID: UUID,
1927        availabilityStatus: DomainAvailabilityStatus?,
1928        updatedAt: Date,
1929        changeSummary: DomainChangeSummary?,
1930        changeSeverity: ChangeSeverity?,
1931        certificateWarningLevel: CertificateWarningLevel,
1932        certificateDaysRemaining: Int?
1933    ) {
1934        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1935            return
1936        }
1937        trackedDomains[index].lastSnapshotID = snapshotID
1938        trackedDomains[index].lastKnownAvailability = availabilityStatus
1939        trackedDomains[index].updatedAt = updatedAt
1940        trackedDomains[index].lastChangeSummary = changeSummary
1941        trackedDomains[index].lastChangeSeverity = changeSeverity
1942        trackedDomains[index].certificateWarningLevel = certificateWarningLevel
1943        trackedDomains[index].certificateDaysRemaining = certificateDaysRemaining
1944        persistTrackedDomains()
1945    }
1946
1947    private func notifyIfNeeded(for entry: HistoryEntry, snapshot: LookupSnapshot, previousSnapshot: LookupSnapshot?) {
1948        guard notificationsAuthorized, entry.trackedDomainID != nil else { return }
1949
1950        Task {
1951            if let summary = entry.changeSummary, summary.hasChanges {
1952                await LocalNotificationService.shared.notifyDomainEvent(
1953                    domain: entry.domain,
1954                    message: summary.message,
1955                    severity: summary.severity
1956                )
1957            }
1958
1959            let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: snapshot)
1960            if certificateWarningLevel == .critical, let daysRemaining = snapshot.sslInfo?.daysUntilExpiry {
1961                await LocalNotificationService.shared.notifyCertificateWarning(
1962                    domain: entry.domain,
1963                    daysRemaining: daysRemaining
1964                )
1965            }
1966
1967            if let previousStatus = previousSnapshot?.availabilityResult?.status,
1968               let newStatus = snapshot.availabilityResult?.status,
1969               previousStatus != newStatus {
1970                await LocalNotificationService.shared.notifyDomainEvent(
1971                    domain: entry.domain,
1972                    message: "Availability changed",
1973                    severity: .high
1974                )
1975            }
1976        }
1977    }
1978
1979    private func previousSnapshot(for domain: String, trackedDomainID: UUID?, replacingLatest: Bool) -> LookupSnapshot? {
1980        let matchingEntries = history.filter { entry in
1981            if let trackedDomainID {
1982                return entry.trackedDomainID == trackedDomainID
1983            }
1984            return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1985        }
1986
1987        if replacingLatest {
1988            return matchingEntries.dropFirst().first?.snapshot
1989        }
1990        return matchingEntries.first?.snapshot
1991    }
1992
1993    private func trackedDomain(for domain: String) -> TrackedDomain? {
1994        trackedDomains.first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }
1995    }
1996
1997    func normalizedDomain(_ domain: String) -> String {
1998        domain
1999            .trimmingCharacters(in: .whitespacesAndNewlines)
2000            .replacingOccurrences(of: "https://", with: "")
2001            .replacingOccurrences(of: "http://", with: "")
2002            .components(separatedBy: "/")
2003            .first?
2004            .lowercased() ?? ""
2005    }
2006
2007    private func linkTrackedDomainHistory(for domain: String) {
2008        guard let trackedDomain = trackedDomain(for: domain) else { return }
2009
2010        var relinked: [HistoryEntry] = []
2011        for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
2012            if history[index].trackedDomainID != trackedDomain.id {
2013                history[index].trackedDomainID = trackedDomain.id
2014                relinked.append(history[index])
2015            }
2016        }
2017
2018        relinked.forEach { updateStoredHistory($0) }
2019
2020        if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
2021           let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
2022            trackedDomains[trackedIndex].lastSnapshotID = latestEntry.id
2023            trackedDomains[trackedIndex].lastChangeSummary = latestEntry.changeSummary
2024            trackedDomains[trackedIndex].lastChangeSeverity = latestEntry.changeSummary?.severity
2025            trackedDomains[trackedIndex].lastKnownAvailability = latestEntry.availabilityResult?.status
2026            trackedDomains[trackedIndex].certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: latestEntry.snapshot)
2027            trackedDomains[trackedIndex].certificateDaysRemaining = latestEntry.sslInfo?.daysUntilExpiry
2028            trackedDomains[trackedIndex].updatedAt = latestEntry.timestamp
2029            persistTrackedDomains()
2030        }
2031    }
2032
2033    func addRecentSearch(_ domain: String) {
2034        recentSearches.removeAll { $0.lowercased() == domain.lowercased() }
2035        recentSearches.insert(domain, at: 0)
2036        if recentSearches.count > Self.maxRecent {
2037            recentSearches = Array(recentSearches.prefix(Self.maxRecent))
2038        }
2039        DomainDataPortabilityService.saveRecentSearches(recentSearches, defaults: defaults)
2040        CloudSyncService.shared.markAppSettingsChanged()
2041        refreshDataLifecycleSummary()
2042    }
2043
2044    func beginLookup(for target: String, cancelExistingTask: Bool = true) -> UUID {
2045        if cancelExistingTask {
2046            lookupTask?.cancel()
2047        }
2048        customPortScanTask?.cancel()
2049
2050        let lookupID = UUID()
2051        activeLookupID = lookupID
2052        lookupStartedAt = Date()
2053        lastLookupDurationMs = nil
2054        addRecentSearch(target)
2055        searchedDomain = target
2056        hasRun = true
2057        currentHistoryEntryID = nil
2058        currentInspectionMetadata = nil
2059        currentSnapshotTimestamp = Date()
2060        currentResultSource = .live
2061        currentCachedSections = []
2062        currentStatusMessage = nil
2063        currentDiffSections = []
2064        currentChangeSummary = nil
2065        currentReport = nil
2066        ownershipDiff = []
2067        clearLookupState()
2068        setAllLoadingStates(true)
2069        return lookupID
2070    }
2071
2072    func startBatchLookup(domains: [String], source: BatchLookupSource, workflow: DomainWorkflow? = nil) {
2073        guard !domains.isEmpty else { return }
2074        guard !batchLookupRunning else { return }
2075
2076        let now = Date()
2077        if let lastBatchStartedAt, now.timeIntervalSince(lastBatchStartedAt) < 1 {
2078            return
2079        }
2080
2081        lastBatchStartedAt = now
2082        clearBatchState()
2083        batchLookupSource = source
2084        activeWorkflowRunID = workflow?.id
2085        activeWorkflowRunName = workflow?.name
2086        batchTotalCount = domains.count
2087        batchLookupRunning = true
2088        batchResults = domains.map {
2089            BatchLookupResult(
2090                domain: $0,
2091                historyEntryID: nil,
2092                availability: nil,
2093                primaryIP: nil,
2094                quickStatus: "Pending",
2095                timestamp: Date(),
2096                status: .pending
2097            )
2098        }
2099
2100        lookupTask?.cancel()
2101        customPortScanTask?.cancel()
2102        batchTask?.cancel()
2103
2104        SweepActivityController.shared.begin(
2105            title: source == .watchlistRefresh ? "Watchlist Sweep" : "Batch Lookup",
2106            total: domains.count
2107        )
2108
2109        batchTask = Task { [weak self] in
2110            guard let self else { return }
2111            self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
2112            await self.runBatchLookup(domains: domains, source: source)
2113        }
2114    }
2115
2116    private func clearBatchState() {
2117        batchResults = []
2118        batchLookupSource = .manual
2119        batchCurrentDomain = nil
2120        batchCompletedCount = 0
2121        batchTotalCount = 0
2122        batchLookupRunning = false
2123        latestBatchSweepSummary = nil
2124        latestWorkflowRunSummary = nil
2125        activeBatchDomains = []
2126        activeWorkflowRunID = nil
2127        activeWorkflowRunName = nil
2128        batchTask = nil
2129    }
2130
2131    /// Splits bulk input into the domains that validate and the entries that do
2132    /// not.
2133    ///
2134    /// The rejected entries are returned rather than dropped: they used to go
2135    /// missing silently, so pasting ten domains with two typos ran eight and
2136    /// said nothing about the other two (U5). Before !8 those entries ran and
2137    /// failed visibly per section, and the single-lookup path has reported its
2138    /// own error since — the asymmetry was the defect.
2139    func parsedBulkInput(from input: String) -> ParsedBulkInput {
2140        let separators = CharacterSet(charactersIn: ",").union(.whitespacesAndNewlines)
2141        var seen = Set<String>()
2142        var domains: [String] = []
2143        var skipped: [String] = []
2144
2145        for token in input.components(separatedBy: separators) {
2146            // Whitespace between entries is not an entry.
2147            guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue }
2148            guard let domain = try? DomainName.validate(token).get() else {
2149                skipped.append(token)
2150                continue
2151            }
2152            if seen.insert(domain).inserted {
2153                domains.append(domain)
2154            }
2155        }
2156
2157        return ParsedBulkInput(domains: domains, skipped: skipped)
2158    }
2159
2160    private func runBatchLookup(domains: [String], source: BatchLookupSource) async {
2161        let concurrencyLimit = min(source == .watchlistRefresh ? 4 : 3, max(domains.count, 1))
2162        var nextIndex = 0
2163        beginBulkPersistenceDeferral()
2164
2165        await withTaskGroup(of: (String, BatchLookupPayload?).self) { group in
2166            for _ in 0..<concurrencyLimit {
2167                guard nextIndex < domains.count else { break }
2168                let domain = domains[nextIndex]
2169                nextIndex += 1
2170                enqueueBatchLookup(domain: domain, source: source, group: &group)
2171            }
2172
2173            while let (domain, payload) = await group.next() {
2174                completeBatchLookup(domain: domain, payload: payload)
2175
2176                if nextIndex < domains.count, !Task.isCancelled {
2177                    let nextDomain = domains[nextIndex]
2178                    nextIndex += 1
2179                    enqueueBatchLookup(domain: nextDomain, source: source, group: &group)
2180                }
2181            }
2182        }
2183
2184        endBulkPersistenceDeferral()
2185        finishBatchLookup(source: source)
2186    }
2187
2188    private func enqueueBatchLookup(
2189        domain: String,
2190        source: BatchLookupSource,
2191        group: inout TaskGroup<(String, BatchLookupPayload?)>
2192    ) {
2193        activeBatchDomains.append(domain)
2194        batchCurrentDomain = activeBatchDomains.first
2195        if source == .watchlistRefresh {
2196            refreshingTrackedDomainID = trackedDomain(for: domain)?.id
2197        }
2198        updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil)
2199        let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false)
2200
2201        group.addTask { [domain, previousSnapshot, scope = InspectionScope.current(defaults: defaults)] in
2202            let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
2203            return (domain, payload)
2204        }
2205    }
2206
2207    private func completeBatchLookup(domain: String, payload: BatchLookupPayload?) {
2208        activeBatchDomains.removeAll { $0.caseInsensitiveCompare(domain) == .orderedSame }
2209        batchCurrentDomain = activeBatchDomains.first
2210
2211        guard let payload else {
2212            updateBatchResult(
2213                domain: domain,
2214                status: .failed,
2215                quickStatus: "Failed",
2216                entry: nil,
2217                resultSource: .live,
2218                errorMessage: "Lookup cancelled"
2219            )
2220            batchCompletedCount += 1
2221            SweepActivityController.shared.update(
2222                completed: batchCompletedCount,
2223                total: batchTotalCount,
2224                currentDomain: batchCurrentDomain
2225            )
2226            return
2227        }
2228
2229        let entry = payload.snapshot.historyEntryID.flatMap { id in
2230            history.first(where: { $0.id == id })
2231        } ?? saveHistoryEntry(from: payload.snapshot, replaceLatest: false, updateCurrentState: false)
2232        let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: payload.snapshot)
2233        let riskAssessment = entry?.changeSummary?.riskAssessment ?? DomainInsightEngine.analyze(snapshot: payload.snapshot).riskAssessment
2234        let quickStatus: String
2235        if entry?.changeSummary?.hasChanges == true {
2236            if entry?.changeSummary?.impactClassification == .critical {
2237                quickStatus = "Critical"
2238            } else {
2239                quickStatus = entry?.changeSummary?.severity == .high ? "High" : "Changed"
2240            }
2241        } else if certificateWarningLevel != .none {
2242            quickStatus = certificateWarningLevel == .critical ? "Critical" : "Warning"
2243        } else if riskAssessment.level == .high {
2244            quickStatus = "High"
2245        } else {
2246            quickStatus = "Unchanged"
2247        }
2248
2249        updateBatchResult(
2250            domain: domain,
2251            status: .completed,
2252            quickStatus: quickStatus,
2253            entry: entry,
2254            resultSource: payload.snapshot.resultSource,
2255            errorMessage: payload.snapshot.statusMessage
2256        )
2257        batchCompletedCount += 1
2258        SweepActivityController.shared.update(
2259            completed: batchCompletedCount,
2260            total: batchTotalCount,
2261            currentDomain: batchCurrentDomain
2262        )
2263    }
2264
2265    private func finishBatchLookup(source: BatchLookupSource) {
2266        batchLookupRunning = false
2267        batchCurrentDomain = nil
2268        activeBatchDomains = []
2269        refreshingTrackedDomainID = nil
2270        batchTask = nil
2271
2272        let changedCount = batchResults.filter { $0.quickStatus == "Changed" || $0.quickStatus == "High" || $0.quickStatus == "Critical" }.count
2273        let unchangedCount = batchResults.filter { $0.quickStatus == "Unchanged" && $0.status == .completed }.count
2274        let warningCount = batchResults.filter {
2275            $0.certificateWarningLevel != .none
2276                || $0.changeClassification == .warning
2277                || $0.changeClassification == .critical
2278                || $0.riskLevel == .high
2279        }.count
2280
2281        let summary = BatchSweepSummary(
2282            source: source,
2283            totalDomains: batchResults.count,
2284            changedDomains: changedCount,
2285            unchangedDomains: unchangedCount,
2286            warningDomains: warningCount,
2287            results: batchResults.sorted { lhs, rhs in
2288                if lhs.status != rhs.status {
2289                    return lhs.status.rawValue < rhs.status.rawValue
2290                }
2291                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2292            },
2293            generatedAt: Date()
2294        )
2295        latestBatchSweepSummary = summary
2296        // Only the domains that actually completed: a failed lookup has no
2297        // report to upload.
2298        IntegrationService.shared.enqueueExports(
2299            domains: batchResults.filter { $0.status == .completed }.map(\.domain),
2300            trigger: .batch
2301        )
2302        SweepActivityController.shared.end(changed: changedCount, warnings: warningCount)
2303        AppAccessibility.announce(
2304            "Sweep complete. \(summary.results.count) domains, \(changedCount) changed, \(warningCount) warnings."
2305        )
2306
2307        if source == .workflow, let activeWorkflowRunID, let activeWorkflowRunName {
2308            let workflowReports: [DomainReport] = summary.results.compactMap { result in
2309                guard let entry = historyEntry(for: result) else { return nil }
2310                return report(for: entry)
2311            }
2312            latestWorkflowRunSummary = WorkflowRunSummary(
2313                workflowID: activeWorkflowRunID,
2314                workflowName: activeWorkflowRunName,
2315                totalDomains: batchResults.count,
2316                changedDomains: changedCount,
2317                unchangedDomains: unchangedCount,
2318                warningDomains: warningCount,
2319                results: summary.results,
2320                workflowInsights: DomainInsightEngine.workflowInsights(for: workflowReports),
2321                generatedAt: summary.generatedAt
2322            )
2323        }
2324
2325        if notificationsAuthorized, source != .workflow {
2326            Task {
2327                await LocalNotificationService.shared.notifySweepComplete(summary: summary)
2328            }
2329        }
2330    }
2331
2332    private func updateBatchResult(
2333        domain: String,
2334        status: BatchLookupStatus,
2335        quickStatus: String,
2336        entry: HistoryEntry?,
2337        resultSource: LookupResultSource = .live,
2338        errorMessage: String?
2339    ) {
2340        guard let index = batchResults.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
2341            return
2342        }
2343
2344        batchResults[index] = BatchLookupResult(
2345            id: batchResults[index].id,
2346            domain: domain,
2347            historyEntryID: entry?.id,
2348            resultSource: resultSource,
2349            availability: entry?.availabilityResult?.status,
2350            primaryIP: entry?.primaryIP,
2351            quickStatus: quickStatus,
2352            summaryMessage: entry?.changeSummary?.message,
2353            changeSeverity: entry?.changeSummary?.severity,
2354            changeClassification: entry?.changeSummary?.impactClassification,
2355            certificateWarningLevel: entry.map { DomainDiffService.certificateWarningLevel(for: $0.snapshot) } ?? batchResults[index].certificateWarningLevel,
2356            riskScore: entry.map { $0.changeSummary?.riskAssessment?.score ?? report(for: $0).riskAssessment.score },
2357            riskLevel: entry.map { $0.changeSummary?.riskAssessment?.level ?? report(for: $0).riskAssessment.level },
2358            timestamp: entry?.timestamp ?? Date(),
2359            status: status,
2360            errorMessage: errorMessage
2361        )
2362    }
2363
2364    /// Resets every section before a new lookup, so the previous domain's
2365    /// results cannot be mistaken for this one's. One assignment per section
2366    /// now; it used to be three.
2367    private func clearLookupState() {
2368        currentInspectionMetadata = nil
2369        dnsState = .idle
2370        availabilityState = .idle
2371        suggestionsState = .idle
2372        sslState = .idle
2373        hstsState = .idle
2374        httpHeadersState = .idle
2375        httpSecurityGrade = nil
2376        httpStatusCode = nil
2377        httpResponseTimeMs = nil
2378        httpProtocol = nil
2379        http3Advertised = false
2380        reachabilityState = .idle
2381        ipGeolocationState = .idle
2382        emailSecurityState = .idle
2383        ownershipState = .idle
2384        ownershipHistoryState = .idle
2385        ptrState = .idle
2386        redirectChainState = .idle
2387        subdomainsState = .idle
2388        extendedSubdomainsState = .idle
2389        dnsHistoryState = .idle
2390        domainPricingState = .idle
2391        reputationState = .idle
2392        portScanState = .idle
2393        customPortScanState = .idle
2394    }
2395
2396    /// Puts the sections a lookup drives into flight, and resets the
2397    /// on-demand ones — ownership history, extended subdomains, DNS history
2398    /// and pricing are fetched when the user opens them, not by the lookup, so
2399    /// they were never part of this either.
2400    private func setAllLoadingStates(_ loading: Bool) {
2401        let phase: SectionPhase = loading ? .loading : .idle
2402        dnsState.phase = phase
2403        availabilityState.phase = phase
2404        suggestionsState.phase = phase
2405        sslState.phase = phase
2406        hstsState.phase = phase
2407        httpHeadersState.phase = phase
2408        reachabilityState.phase = phase
2409        ipGeolocationState.phase = phase
2410        emailSecurityState.phase = phase
2411        ownershipState.phase = phase
2412        ptrState.phase = phase
2413        redirectChainState.phase = phase
2414        subdomainsState.phase = phase
2415        portScanState.phase = phase
2416
2417        ownershipHistoryState.phase = .idle
2418        extendedSubdomainsState.phase = .idle
2419        dnsHistoryState.phase = .idle
2420        domainPricingState.phase = .idle
2421    }
2422
2423    private func primaryIPAddress(from sections: [DNSSection]) -> String? {
2424        sections.first(where: { $0.recordType == .A })?.records.first?.value
2425    }
2426
2427    func isCurrentLookup(_ lookupID: UUID) -> Bool {
2428        activeLookupID == lookupID
2429    }
2430
2431    func recentSnapshots(for trackedDomain: TrackedDomain, limit: Int = 6) -> [HistoryEntry] {
2432        history
2433            .filter { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
2434            .sorted { $0.timestamp > $1.timestamp }
2435            .prefix(limit)
2436            .map { $0 }
2437    }
2438
2439    func latestSnapshots(for domains: [TrackedDomain]) -> [HistoryEntry] {
2440        domains.compactMap { trackedDomain in
2441            recentSnapshots(for: trackedDomain, limit: 1).first
2442        }
2443    }
2444
2445    func diffSectionsForLatestSnapshots(of trackedDomain: TrackedDomain) -> [DomainDiffSection] {
2446        let snapshots = recentSnapshots(for: trackedDomain, limit: 2)
2447        guard snapshots.count == 2 else { return [] }
2448        return DomainDiffService.diff(from: snapshots[1].snapshot, to: snapshots[0].snapshot)
2449    }
2450
2451    func latestChangeSummary(for trackedDomain: TrackedDomain) -> DomainChangeSummary? {
2452        trackedDomain.lastChangeSummary ?? recentSnapshots(for: trackedDomain, limit: 1).first?.changeSummary
2453    }
2454
2455    func latestSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot? {
2456        recentSnapshots(for: trackedDomain, limit: 1).first?.snapshot
2457    }
2458
2459    func trackedDomain(withID id: UUID) -> TrackedDomain? {
2460        trackedDomains.first(where: { $0.id == id })
2461    }
2462
2463    private func buildPortfolioDomainStates() -> [PortfolioDomainStatus] {
2464        let now = Date()
2465        return sortedTrackedDomains(from: trackedDomains, using: .pinned).map { trackedDomain in
2466            let recentEntries = recentSnapshots(for: trackedDomain, limit: 8)
2467            let latestEntry = recentEntries.first
2468            let report = latestEntry.map { self.report(for: $0) } ?? reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
2469            let recentMonitoringResults = monitoringLogs
2470                .flatMap(\.checkedDomains)
2471                .filter { $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
2472                .sorted { $0.checkedAt > $1.checkedAt }
2473            let recentFailureResults = recentMonitoringResults.filter {
2474                let isFailure = $0.errorMessage != nil || ($0.alertSeverity ?? .info) >= .warning
2475                return isFailure && now.timeIntervalSince($0.checkedAt) <= 7 * 24 * 60 * 60
2476            }
2477            let recentChangeCount = recentEntries.filter {
2478                guard let changeSummary = $0.changeSummary, changeSummary.hasChanges else { return false }
2479                return now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2480            }.count
2481            let recentDNSChange = recentEntries.contains {
2482                guard let changeSummary = $0.changeSummary else { return false }
2483                return changeSummary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") })
2484                    && now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2485            }
2486            let recentCriticalChange = recentEntries.contains {
2487                guard let changeSummary = $0.changeSummary else { return false }
2488                return changeSummary.impactClassification == .critical
2489                    && now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2490            }
2491            let certificateExpiryState = trackedDomain.certificateWarningLevel == .none
2492                ? report.certificateExpiryState
2493                : trackedDomain.certificateWarningLevel
2494            let isUnreachable: Bool = {
2495                if let latestEntry {
2496                    if !latestEntry.reachabilityResults.isEmpty {
2497                        return !latestEntry.reachabilityResults.contains(where: \.reachable)
2498                    }
2499                    if latestEntry.reachabilityError != nil {
2500                        return true
2501                    }
2502                }
2503                return recentFailureResults.contains { ($0.alertSeverity ?? .info) == .critical && $0.errorMessage != nil }
2504            }()
2505            let hasInvalidTLS = latestEntry?.sslInfo == nil && latestEntry?.sslError != nil
2506            let instabilityScore = DomainHealth.instabilityScore(
2507                recentChangeCount: recentChangeCount,
2508                recentFailureCount: recentFailureResults.count,
2509                pendingAlertCount: trackedDomain.pendingMonitoringAlerts.count,
2510                hasRecentDNSChange: recentDNSChange
2511            )
2512            let health = DomainHealth.classify(
2513                certificateExpiryState: certificateExpiryState,
2514                isReachable: !isUnreachable,
2515                recentMonitoringFailureCount: recentFailureResults.count,
2516                hasRecentDNSChange: recentDNSChange,
2517                instabilityScore: instabilityScore,
2518                hasRecentCriticalChange: recentCriticalChange,
2519                hasInvalidTLS: hasInvalidTLS
2520            )
2521
2522            return PortfolioDomainStatus(
2523                trackedDomain: trackedDomain,
2524                latestEntry: latestEntry,
2525                report: report,
2526                apexDomain: apexDomain(for: trackedDomain.domain),
2527                health: health,
2528                lastChangeDate: latestEntry?.changeSummary?.hasChanges == true
2529                    ? latestEntry?.timestamp
2530                    : trackedDomain.monitoringState.lastChangeDate ?? report.lastChangeDate,
2531                lastMonitoringFailure: recentFailureResults.first?.checkedAt,
2532                instabilityScore: instabilityScore,
2533                certificateExpiryState: certificateExpiryState,
2534                certificateDaysRemaining: trackedDomain.certificateDaysRemaining ?? latestEntry?.sslInfo?.daysUntilExpiry,
2535                isUnreachable: isUnreachable,
2536                recentDNSChange: recentDNSChange,
2537                recentCriticalChange: recentCriticalChange,
2538                recentFailureCount: recentFailureResults.count
2539            )
2540        }
2541    }
2542
2543    private func buildPortfolioActivity(from domainStates: [PortfolioDomainStatus]) -> [PortfolioActivityItem] {
2544        var items: [PortfolioActivityItem] = []
2545        let healthByDomainID = Dictionary(uniqueKeysWithValues: domainStates.map { ($0.trackedDomain.id, $0.health) })
2546
2547        for state in domainStates {
2548            if let latestEntry = state.latestEntry,
2549               let changeSummary = latestEntry.changeSummary,
2550               changeSummary.hasChanges {
2551                items.append(
2552                    PortfolioActivityItem(
2553                        id: "history|\(latestEntry.id.uuidString)",
2554                        trackedDomainID: state.trackedDomain.id,
2555                        domain: state.trackedDomain.domain,
2556                        message: portfolioHistoryMessage(for: latestEntry),
2557                        timestamp: latestEntry.timestamp,
2558                        health: state.health,
2559                        systemImage: portfolioHistoryIcon(for: latestEntry)
2560                    )
2561                )
2562            }
2563        }
2564
2565        for log in monitoringLogs.prefix(25) {
2566            for result in log.checkedDomains where result.didChange || result.errorMessage != nil || result.certificateWarningLevel != .none {
2567                guard let trackedDomain = trackedDomain(for: result.domain) else { continue }
2568                items.append(
2569                    PortfolioActivityItem(
2570                        id: "monitoring|\(log.id.uuidString)|\(result.id.uuidString)",
2571                        trackedDomainID: trackedDomain.id,
2572                        domain: trackedDomain.domain,
2573                        message: portfolioMonitoringMessage(for: result),
2574                        timestamp: result.checkedAt,
2575                        health: healthByDomainID[trackedDomain.id] ?? (result.alertSeverity == .critical ? .critical : .warning),
2576                        systemImage: portfolioMonitoringIcon(for: result)
2577                    )
2578                )
2579            }
2580        }
2581
2582        var seen = Set<String>()
2583        return items
2584            .sorted { $0.timestamp > $1.timestamp }
2585            .filter { item in
2586                let key = "\(item.domain.lowercased())|\(item.message.lowercased())"
2587                return seen.insert(key).inserted
2588            }
2589    }
2590
2591    private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
2592        domainStates.compactMap { state in
2593            guard state.health != .healthy else { return nil }
2594            let (reason, timestamp) = Self.attentionReason(for: state)
2595            return PortfolioAttentionItem(
2596                id: "\(state.trackedDomain.id.uuidString)|\(reason)",
2597                trackedDomainID: state.trackedDomain.id,
2598                domain: state.trackedDomain.domain,
2599                reason: reason,
2600                timestamp: timestamp,
2601                health: state.health
2602            )
2603        }
2604        .sorted { lhs, rhs in
2605            if lhs.health != rhs.health {
2606                return lhs.health.severityRank > rhs.health.severityRank
2607            }
2608            return lhs.timestamp > rhs.timestamp
2609        }
2610    }
2611
2612    /// Why an unhealthy domain needs attention, most urgent cause first, and
2613    /// when that cause was last seen.
2614    private static func attentionReason(for state: PortfolioDomainStatus) -> (reason: String, timestamp: Date) {
2615        let changedAt = state.lastChangeDate ?? state.trackedDomain.updatedAt
2616        let failedAt = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2617        if state.isUnreachable {
2618            return ("Endpoint is unreachable", failedAt)
2619        }
2620        if state.certificateExpiryState == .critical {
2621            return ("Certificate is expiring in under 14 days", changedAt)
2622        }
2623        if state.certificateExpiryState == .warning {
2624            return ("Certificate expires within 30 days", changedAt)
2625        }
2626        if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2627            return ("Repeated instability detected", failedAt)
2628        }
2629        if state.recentDNSChange {
2630            return ("DNS changed recently", changedAt)
2631        }
2632        if state.recentCriticalChange {
2633            return ("Recent critical change detected", changedAt)
2634        }
2635        return ("Needs attention", state.trackedDomain.updatedAt)
2636    }
2637
2638    private func portfolioHistoryMessage(for entry: HistoryEntry) -> String {
2639        guard let summary = entry.changeSummary else {
2640            return "Configuration changed for \(entry.domain)"
2641        }
2642        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") }) {
2643            return "DNS changed for \(entry.domain)"
2644        }
2645        if summary.changedSections.contains(where: {
2646            $0.localizedCaseInsensitiveContains("certificate")
2647                || $0.localizedCaseInsensitiveContains("tls")
2648        }) {
2649            return "Certificate updated for \(entry.domain)"
2650        }
2651        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("redirect") }) {
2652            return "Redirect chain changed for \(entry.domain)"
2653        }
2654        return summary.message
2655    }
2656
2657    private func portfolioHistoryIcon(for entry: HistoryEntry) -> String {
2658        guard let summary = entry.changeSummary else { return "clock.arrow.trianglehead.counterclockwise.rotate.90" }
2659        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") }) {
2660            return "point.3.connected.trianglepath.dotted"
2661        }
2662        if summary.changedSections.contains(where: {
2663            $0.localizedCaseInsensitiveContains("certificate")
2664                || $0.localizedCaseInsensitiveContains("tls")
2665        }) {
2666            return "lock.rotation"
2667        }
2668        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("redirect") }) {
2669            return "arrow.triangle.branch"
2670        }
2671        return "clock.arrow.trianglehead.counterclockwise.rotate.90"
2672    }
2673
2674    private func portfolioMonitoringMessage(for result: MonitoringDomainResult) -> String {
2675        if result.errorMessage != nil {
2676            return "Monitoring failed for \(result.domain)"
2677        }
2678        if result.certificateWarningLevel != .none {
2679            return "Certificate needs attention for \(result.domain)"
2680        }
2681        if result.didChange {
2682            return result.summaryMessage.isEmpty ? "Monitoring detected a change for \(result.domain)" : result.summaryMessage
2683        }
2684        return "Monitoring updated \(result.domain)"
2685    }
2686
2687    private func portfolioMonitoringIcon(for result: MonitoringDomainResult) -> String {
2688        if result.errorMessage != nil {
2689            return "xmark.octagon.fill"
2690        }
2691        if result.certificateWarningLevel != .none {
2692            return "exclamationmark.triangle.fill"
2693        }
2694        return "waveform.path.ecg"
2695    }
2696
2697    private func apexDomain(for domain: String) -> String {
2698        let parts = domain
2699            .lowercased()
2700            .split(separator: ".")
2701            .map(String.init)
2702        guard parts.count > 2 else { return domain.lowercased() }
2703        return parts.suffix(2).joined(separator: ".")
2704    }
2705
2706    private func exportSnapshots(for domains: [TrackedDomain]) -> [LookupSnapshot] {
2707        let latestEntries = latestSnapshots(for: domains)
2708
2709        return domains.map { trackedDomain in
2710            if let entry = latestEntries.first(where: { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }) {
2711                return entry.snapshot
2712            }
2713            return placeholderSnapshot(for: trackedDomain)
2714        }
2715    }
2716
2717    func currentBatchReports() -> [DomainReport] {
2718        currentBatchResultEntries.map { entry in
2719            report(for: entry, workflowContext: activeWorkflowContext)
2720        }
2721    }
2722
2723    func workflowReports(from summary: WorkflowRunSummary, changedOnly: Bool) -> [DomainReport] {
2724        let filteredResults = changedOnly ? summary.results.filter(\.hasMeaningfulChange) : summary.results
2725        return filteredResults.compactMap { result in
2726            guard let entry = historyEntry(for: result) else { return nil }
2727            return report(
2728                for: entry,
2729                workflowContext: DomainWorkflowContext(
2730                    workflowID: summary.workflowID,
2731                    workflowName: summary.workflowName,
2732                    source: "workflow"
2733                )
2734            )
2735        }
2736    }
2737
2738    func reports(for domains: [TrackedDomain]) -> [DomainReport] {
2739        let latestEntries = latestSnapshots(for: domains)
2740
2741        return domains.map { trackedDomain in
2742            if let entry = latestEntries.first(where: {
2743                $0.trackedDomainID == trackedDomain.id ||
2744                $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame
2745            }) {
2746                return report(for: entry)
2747            }
2748
2749            return reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
2750        }
2751    }
2752
2753    func timelineReports(for domain: String) -> [DomainReport] {
2754        historyEntries(for: domain).map { report(for: $0) }
2755    }
2756
2757    private func report(for entry: HistoryEntry, workflowContext: DomainWorkflowContext? = nil) -> DomainReport {
2758        reportBuilder.build(
2759            from: entry,
2760            previousSnapshot: comparisonSnapshot(for: entry),
2761            workflowContext: workflowContext,
2762            historyEntries: historyEntries(for: entry.domain)
2763        )
2764    }
2765
2766    private var activeWorkflowContext: DomainWorkflowContext? {
2767        guard batchLookupSource == .workflow, let activeWorkflowRunID, let activeWorkflowRunName else {
2768            return nil
2769        }
2770        return DomainWorkflowContext(
2771            workflowID: activeWorkflowRunID,
2772            workflowName: activeWorkflowRunName,
2773            source: "workflow"
2774        )
2775    }
2776
2777    private static var defaultAuditReviewer: String {
2778        let reviewer = NSFullUserName().trimmingCharacters(in: .whitespacesAndNewlines)
2779        return reviewer.isEmpty ? "Local Reviewer" : reviewer
2780    }
2781
2782    private func snapshotEvidenceAssets(from report: DomainReport) -> [AuditEvidenceAsset] {
2783        var assets: [AuditEvidenceAsset] = []
2784        if let finalURL = report.web.finalURL {
2785            assets.append(AuditEvidenceAsset(title: "Final URL", kind: .document, reference: finalURL))
2786        }
2787        if let registrar = report.ownership?.registrar {
2788            assets.append(AuditEvidenceAsset(title: "Registrar", kind: .document, reference: registrar))
2789        }
2790        if let primaryIP = report.dns.primaryIP {
2791            assets.append(AuditEvidenceAsset(title: "Primary IP", kind: .document, reference: primaryIP))
2792        }
2793        if !report.web.redirectChain.isEmpty {
2794            assets.append(
2795                AuditEvidenceAsset(
2796                    title: "Redirect Chain",
2797                    kind: .document,
2798                    reference: report.web.redirectChain.map { "\($0.statusCode) \($0.url)" }.joined(separator: " | ")
2799                )
2800            )
2801        }
2802        if !report.web.headers.isEmpty {
2803            assets.append(
2804                AuditEvidenceAsset(
2805                    title: "Observed Headers",
2806                    kind: .document,
2807                    reference: report.web.headers.prefix(6).map { "\($0.name): \($0.value)" }.joined(separator: " | ")
2808                )
2809            )
2810        }
2811        return assets
2812    }
2813
2814    private func placeholderSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot {
2815        LookupSnapshot(
2816            historyEntryID: trackedDomain.lastSnapshotID,
2817            domain: trackedDomain.domain,
2818            timestamp: trackedDomain.updatedAt,
2819            trackedDomainID: trackedDomain.id,
2820            note: trackedDomain.note,
2821            appVersion: AppVersion.current,
2822            resolverDisplayName: resolverDisplayName,
2823            resolverURLString: resolverURLString,
2824            dataSources: [],
2825            provenanceBySection: [:],
2826            availabilityConfidence: nil,
2827            ownershipConfidence: nil,
2828            subdomainConfidence: nil,
2829            emailSecurityConfidence: nil,
2830            geolocationConfidence: nil,
2831            errorDetails: [:],
2832            isPartialSnapshot: true,
2833            validationIssues: ["No stored snapshot data available"],
2834            totalLookupDurationMs: nil,
2835            snapshotIndex: nil,
2836            previousSnapshotID: nil,
2837            changeCount: 0,
2838            severitySummary: trackedDomain.lastChangeSeverity,
2839            dnsSections: [],
2840            dnsError: nil,
2841            availabilityResult: DomainAvailabilityResult(domain: trackedDomain.domain, status: trackedDomain.lastKnownAvailability ?? .unknown),
2842            suggestions: [],
2843            sslInfo: nil,
2844            sslError: nil,
2845            hstsPreloaded: nil,
2846            httpHeaders: [],
2847            httpSecurityGrade: nil,
2848            httpStatusCode: nil,
2849            httpResponseTimeMs: nil,
2850            httpProtocol: nil,
2851            http3Advertised: false,
2852            httpHeadersError: nil,
2853            reachabilityResults: [],
2854            reachabilityError: nil,
2855            ipGeolocation: nil,
2856            ipGeolocationError: nil,
2857            emailSecurity: nil,
2858            emailSecurityError: nil,
2859            ownership: nil,
2860            ownershipError: nil,
2861            ownershipHistory: [],
2862            ownershipHistoryError: nil,
2863            inferredProvider: nil,
2864            priorProviders: [],
2865            domainClassification: nil,
2866            ownershipTransitions: [],
2867            hostingTransitions: [],
2868            subdomainHistory: [],
2869            riskSignals: [],
2870            intelligenceTimeline: [],
2871            ptrRecord: nil,
2872            ptrError: nil,
2873            redirectChain: [],
2874            redirectChainError: nil,
2875            subdomains: [],
2876            subdomainsError: nil,
2877            extendedSubdomains: [],
2878            extendedSubdomainsError: nil,
2879            dnsHistory: [],
2880            dnsHistoryError: nil,
2881            domainPricing: nil,
2882            domainPricingError: nil,
2883            reputation: nil,
2884            reputationError: nil,
2885            portScanResults: [],
2886            portScanError: nil,
2887            changeSummary: trackedDomain.lastChangeSummary,
2888            resultSource: .snapshot,
2889            cachedSections: [],
2890            statusMessage: nil
2891        )
2892    }
2893
2894    private static func loadHistoryEntries(
2895        defaults: UserDefaults,
2896        historyLocation: HistoryFileStore.Location
2897    ) -> [HistoryEntry] {
2898        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2899        return DomainDataPortabilityService.loadHistoryEntries(
2900            defaults: defaults,
2901            historyLocation: historyLocation
2902        )
2903    }
2904
2905    private static func loadHistoryAutoPruneOption(defaults: UserDefaults) -> HistoryAutoPruneOption {
2906        guard let rawValue = defaults.string(forKey: historyAutoPruneKey),
2907              let option = HistoryAutoPruneOption(rawValue: rawValue) else {
2908            return .unlimited
2909        }
2910        return option
2911    }
2912
2913    private static func loadTrackedDomains(
2914        defaults: UserDefaults,
2915        historyLocation: HistoryFileStore.Location
2916    ) -> [TrackedDomain] {
2917        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2918        return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
2919    }
2920
2921    func persistWorkflows() {
2922        DomainDataPortabilityService.saveWorkflows(workflows, defaults: defaults)
2923        CloudSyncService.shared.scheduleSyncIfNeeded()
2924        refreshDataLifecycleSummary()
2925    }
2926
2927    static func loadWorkflows(
2928        defaults: UserDefaults,
2929        historyLocation: HistoryFileStore.Location
2930    ) -> [DomainWorkflow] {
2931        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2932        return DomainDataPortabilityService.loadWorkflows(defaults: defaults)
2933    }
2934
2935    private static func deduplicatedTrackedDomains(_ domains: [TrackedDomain]) -> [TrackedDomain] {
2936        var seen = Set<String>()
2937        return domains.filter { domain in
2938            let key = domain.domain.lowercased()
2939            return seen.insert(key).inserted
2940        }
2941    }
2942
2943    func normalizedDomains(_ domains: [String]) -> [String] {
2944        var seen = Set<String>()
2945        return domains
2946            .map(normalizedDomain)
2947            .filter { !$0.isEmpty }
2948            .filter { seen.insert($0).inserted }
2949    }
2950
2951    private func historySortPredicate(lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
2952        switch historySortOption {
2953        case .newest:
2954            return lhs.timestamp > rhs.timestamp
2955        case .oldest:
2956            return lhs.timestamp < rhs.timestamp
2957        case .domain:
2958            let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
2959            if domainOrder != .orderedSame {
2960                return domainOrder == .orderedAscending
2961            }
2962            return lhs.timestamp > rhs.timestamp
2963        }
2964    }
2965
2966    private func sortedTrackedDomains(from domains: [TrackedDomain], using sortOption: WatchlistSortOption) -> [TrackedDomain] {
2967        domains.sorted { lhs, rhs in
2968            switch sortOption {
2969            case .pinned:
2970                if lhs.isPinned != rhs.isPinned {
2971                    return lhs.isPinned && !rhs.isPinned
2972                }
2973                if lhs.updatedAt != rhs.updatedAt {
2974                    return lhs.updatedAt > rhs.updatedAt
2975                }
2976                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2977            case .recentlyUpdated:
2978                if lhs.updatedAt != rhs.updatedAt {
2979                    return lhs.updatedAt > rhs.updatedAt
2980                }
2981                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2982            case .alphabetical:
2983                let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
2984                if domainOrder != .orderedSame {
2985                    return domainOrder == .orderedAscending
2986                }
2987                return lhs.updatedAt > rhs.updatedAt
2988            }
2989        }
2990    }
2991
2992    static func summaryFields(from snapshot: LookupSnapshot) -> [SummaryFieldViewData] {
2993        [
2994            SummaryFieldViewData(label: "Domain", value: snapshot.domain.nilIfEmpty ?? "Unavailable", tone: .primary),
2995            SummaryFieldViewData(label: "Observed IP", value: primaryIPAddress(from: snapshot) ?? "Unavailable", tone: .primary),
2996            SummaryFieldViewData(label: "Observed Redirect", value: finalRedirectTarget(from: snapshot) ?? "Unavailable", tone: .secondary),
2997            SummaryFieldViewData(label: "Inference", value: availabilityInference(from: snapshot), tone: availabilityTone(snapshot.availabilityResult?.status)),
2998            SummaryFieldViewData(label: "Observed TLS", value: httpsSummary(from: snapshot), tone: httpsSummaryTone(from: snapshot)),
2999            SummaryFieldViewData(label: "Certificate", value: certificateStatusLabel(from: snapshot), tone: certificateStatusTone(from: snapshot)),
3000            SummaryFieldViewData(label: "Source", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot))
3001        ]
3002    }
3003
3004    static func domainRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3005        var rows = [
3006            InfoRowViewData(label: "Domain", value: snapshot.domain, tone: .primary),
3007            InfoRowViewData(label: "Resolver", value: snapshot.resolverDisplayName, tone: .secondary),
3008            InfoRowViewData(label: "Collected", value: snapshot.timestamp.formatted(date: .abbreviated, time: .shortened), tone: .secondary),
3009            InfoRowViewData(label: snapshot.statusMessage == nil ? "Result" : "Snapshot", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot)),
3010            InfoRowViewData(label: "Lookup Duration", value: durationLabel(snapshot.totalLookupDurationMs), tone: .secondary)
3011        ]
3012        rows.insert(
3013            InfoRowViewData(
3014                label: "Observed Availability",
3015                value: snapshot.availabilityResult?.status == .unknown ? "No direct registration proof" : "Status collected",
3016                tone: .secondary
3017            ),
3018            at: 1
3019        )
3020        rows.insert(
3021            InfoRowViewData(
3022                label: "Inference",
3023                value: availabilityInference(from: snapshot),
3024                tone: availabilityTone(snapshot.availabilityResult?.status)
3025            ),
3026            at: 2
3027        )
3028        if let confidence = snapshot.availabilityConfidence {
3029            rows.insert(
3030                InfoRowViewData(label: "Confidence", value: confidence.title, tone: .secondary),
3031                at: 3
3032            )
3033        }
3034        if let pricing = snapshot.domainPricing {
3035            rows += pricingRows(pricing)
3036        }
3037        if let reputation = snapshot.reputation {
3038            rows.append(reputationRow(reputation))
3039        }
3040        if let certificateStatus = certificateBadgeLabel(from: snapshot) {
3041            rows.insert(
3042                InfoRowViewData(
3043                    label: "Certificate",
3044                    value: certificateStatus,
3045                    tone: certificateStatusTone(from: snapshot)
3046                ),
3047                at: 2
3048            )
3049        }
3050        return rows
3051    }
3052
3053    private static func pricingRows(_ pricing: DomainPricingInsight) -> [InfoRowViewData] {
3054        var rows = [InfoRowViewData(label: "External Price", value: pricing.estimatedPrice ?? "Unavailable", tone: .secondary)]
3055        if let premiumIndicator = pricing.premiumIndicator {
3056            rows.append(
3057                InfoRowViewData(
3058                    label: "Premium",
3059                    value: premiumIndicator ? "Yes" : "No",
3060                    tone: premiumIndicator ? .warning : .secondary
3061                )
3062            )
3063        }
3064        if let resaleSignal = pricing.resaleSignal {
3065            rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3066        }
3067        if let auctionSignal = pricing.auctionSignal {
3068            rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3069        }
3070        return rows
3071    }
3072
3073    private static func reputationRow(_ reputation: DomainReputationResult) -> InfoRowViewData {
3074        let tone: ResultTone
3075        switch reputation.status {
3076        case .clean: tone = .success
3077        case .listed: tone = .failure
3078        case .unknown: tone = .secondary
3079        }
3080        let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3081            ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3082            : reputation.status.title
3083        return InfoRowViewData(label: "Reputation", value: value, tone: tone)
3084    }
3085
3086    static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
3087        snapshot.suggestions.map {
3088            DomainSuggestionViewData(
3089                id: $0.id,
3090                domain: $0.domain,
3091                availabilityStatus: $0.status,
3092                status: availabilityLabel($0.status),
3093                tone: availabilityTone($0.status)
3094            )
3095        }
3096    }
3097
3098    static func subdomainRows(from subdomains: [DiscoveredSubdomain]) -> [SubdomainRowViewData] {
3099        subdomains.map { subdomain in
3100            SubdomainRowViewData(
3101                hostname: subdomain.hostname,
3102                isInteresting: subdomain.isExtended || isInterestingSubdomain(subdomain.hostname)
3103            )
3104        }
3105    }
3106
3107    static func dnsRows(from snapshot: LookupSnapshot) -> [DNSRecordSectionViewData] {
3108        snapshot.dnsSections.map { section in
3109            DNSRecordSectionViewData(
3110                title: section.recordType.rawValue,
3111                rows: section.records.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary, speechStyle: .technical) },
3112                wildcardRows: section.wildcardRecords.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary, speechStyle: .technical) },
3113                wildcardTitle: section.wildcardRecords.isEmpty ? nil : "*.\(snapshot.domain)",
3114                message: section.error.map { SectionMessageViewData(text: $0, isError: true) } ??
3115                    ((section.records.isEmpty && section.wildcardRecords.isEmpty) ? SectionMessageViewData(text: "No records found", isError: false) : nil)
3116            )
3117        }
3118    }
3119
3120    static func dnssecLabel(from snapshot: LookupSnapshot) -> String? {
3121        guard let signed = snapshot.dnsSections.compactMap(\.dnssecSigned).first else { return nil }
3122        return "Resolver-reported DNSSEC (not full validation): \(signed ? "Yes" : "No")"
3123    }
3124
3125    static func ptrMessage(from snapshot: LookupSnapshot) -> SectionMessageViewData? {
3126        if let ptrRecord = snapshot.ptrRecord {
3127            return SectionMessageViewData(text: ptrRecord, isError: false)
3128        }
3129        if let ptrError = snapshot.ptrError {
3130            return SectionMessageViewData(text: ptrError, isError: ptrError != "No A record available" && ptrError != "No PTR record found")
3131        }
3132        return nil
3133    }
3134
3135    static func webCertificateRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3136        guard let sslInfo = snapshot.sslInfo else { return [] }
3137        var rows = [
3138            InfoRowViewData(label: "Common Name", value: sslInfo.commonName, tone: .primary),
3139            InfoRowViewData(label: "Issuer", value: sslInfo.issuer, tone: .primary),
3140            InfoRowViewData(label: "Valid From", value: certificateDateFormatter.string(from: sslInfo.validFrom), tone: .secondary),
3141            InfoRowViewData(label: "Valid Until", value: certificateDateFormatter.string(from: sslInfo.validUntil), tone: .secondary),
3142            InfoRowViewData(label: "Days Until Expiry", value: "\(sslInfo.daysUntilExpiry)", tone: certificateTone(daysRemaining: sslInfo.daysUntilExpiry)),
3143            InfoRowViewData(label: "Chain Depth", value: "\(sslInfo.chainDepth)", tone: .secondary)
3144        ]
3145        if let tlsVersion = sslInfo.tlsVersion {
3146            rows.append(InfoRowViewData(label: "TLS Version", value: tlsVersion, tone: .secondary))
3147        }
3148        if let cipherSuite = sslInfo.cipherSuite {
3149            rows.append(InfoRowViewData(label: "Cipher Suite", value: cipherSuite, tone: .secondary, speechStyle: .technical))
3150        }
3151        if let hstsPreloaded = snapshot.hstsPreloaded {
3152            rows.append(InfoRowViewData(label: "HSTS Preload", value: hstsPreloaded ? "Preloaded" : "Not preloaded", tone: hstsPreloaded ? .success : .secondary))
3153        }
3154        return rows
3155    }
3156
3157    static func webResponseRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3158        var rows: [InfoRowViewData] = []
3159        if let httpStatusCode = snapshot.httpStatusCode {
3160            rows.append(InfoRowViewData(label: "Status", value: "\(httpStatusCode)", tone: .primary))
3161        }
3162        if let httpResponseTimeMs = snapshot.httpResponseTimeMs {
3163            rows.append(InfoRowViewData(label: "Response Time", value: "\(httpResponseTimeMs) ms", tone: .secondary))
3164        }
3165        if let httpProtocol = snapshot.httpProtocol {
3166            rows.append(InfoRowViewData(label: "Protocol", value: httpProtocol, tone: .secondary))
3167        }
3168        if let httpSecurityGrade = snapshot.httpSecurityGrade {
3169            rows.append(InfoRowViewData(label: "Security Grade", value: httpSecurityGrade, tone: securityGradeTone(httpSecurityGrade)))
3170        }
3171        if snapshot.http3Advertised {
3172            rows.append(InfoRowViewData(label: "HTTP/3", value: "Advertised", tone: .secondary))
3173        }
3174        return rows
3175    }
3176
3177    static func redirectRows(from snapshot: LookupSnapshot) -> [RedirectHopViewData] {
3178        snapshot.redirectChain.map {
3179            RedirectHopViewData(
3180                stepLabel: "\($0.stepNumber)",
3181                statusCode: "\($0.statusCode)",
3182                url: $0.url,
3183                isFinal: $0.isFinal
3184            )
3185        }
3186    }
3187
3188    static func emailRows(from snapshot: LookupSnapshot) -> [EmailRowViewData] {
3189        guard let emailSecurity = snapshot.emailSecurity else { return [] }
3190        return [
3191            EmailRowViewData(label: "SPF", status: emailSecurity.spf.found ? "Present" : "Missing", statusTone: emailSecurity.spf.found ? .success : .warning, detail: emailSecurity.spf.value ?? "No record found", auxiliaryDetail: nil),
3192            EmailRowViewData(label: "DMARC", status: emailSecurity.dmarc.found ? "Present" : "Missing", statusTone: emailSecurity.dmarc.found ? .success : .warning, detail: emailSecurity.dmarc.value ?? "No record found", auxiliaryDetail: nil),
3193            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)" }),
3194            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),
3195            EmailRowViewData(label: "BIMI", status: emailSecurity.bimi.found ? "Present" : "Missing", statusTone: emailSecurity.bimi.found ? .success : .warning, detail: emailSecurity.bimi.value ?? "No record found", auxiliaryDetail: nil)
3196        ]
3197    }
3198
3199    static func ownershipRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3200        let ownership = snapshot.ownership
3201
3202        return [
3203            InfoRowViewData(label: "Registrar", value: ownership?.registrar ?? "Unavailable", tone: ownership?.registrar == nil ? .secondary : .primary),
3204            InfoRowViewData(label: "Registered", value: ownership?.createdDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.createdDate == nil ? .secondary : .primary),
3205            InfoRowViewData(label: "Expires", value: ownership?.expirationDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.expirationDate == nil ? .secondary : .primary),
3206            InfoRowViewData(label: "Status", value: ownership?.status.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.status.isEmpty == false ? .primary : .secondary),
3207            InfoRowViewData(label: "Nameservers", value: ownership?.nameservers.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.nameservers.isEmpty == false ? .primary : .secondary),
3208            InfoRowViewData(label: "Abuse Contact", value: ownership?.abuseEmail ?? "Unavailable", tone: ownership?.abuseEmail == nil ? .secondary : .primary)
3209        ]
3210    }
3211
3212    static func subdomainRows(from snapshot: LookupSnapshot) -> [SubdomainRowViewData] {
3213        snapshot.subdomains.map { subdomain in
3214            SubdomainRowViewData(
3215                hostname: subdomain.hostname,
3216                isInteresting: isInterestingSubdomain(subdomain.hostname)
3217            )
3218        }
3219    }
3220
3221    static func reachabilityRows(from snapshot: LookupSnapshot) -> [ReachabilityRowViewData] {
3222        snapshot.reachabilityResults.map {
3223            ReachabilityRowViewData(
3224                portLabel: "Port \($0.port)",
3225                latencyLabel: $0.latencyMs.map { "\($0) ms" } ?? "—",
3226                statusLabel: $0.reachable ? "Reachable" : "Unreachable",
3227                statusTone: $0.reachable ? .success : .failure
3228            )
3229        }
3230    }
3231
3232    static func locationRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3233        guard let ipGeolocation = snapshot.ipGeolocation else { return [] }
3234        var rows = [InfoRowViewData(label: "IP", value: ipGeolocation.ip, tone: .primary)]
3235        if let org = ipGeolocation.org {
3236            rows.append(InfoRowViewData(label: "Org / ISP", value: org, tone: .secondary))
3237        }
3238        let location = [ipGeolocation.city, ipGeolocation.region, ipGeolocation.countryName].compactMap { $0 }.joined(separator: ", ")
3239        if !location.isEmpty {
3240            rows.append(InfoRowViewData(label: "Location", value: location, tone: .secondary))
3241        }
3242        if let latitude = ipGeolocation.latitude, let longitude = ipGeolocation.longitude {
3243            rows.append(InfoRowViewData(label: "Coordinates", value: "\(latitude), \(longitude)", tone: .secondary))
3244        }
3245        return rows
3246    }
3247
3248    static func portRows(from snapshot: LookupSnapshot, kind: PortScanKind) -> [PortScanRowViewData] {
3249        snapshot.portScanResults
3250            .filter { $0.kind == kind }
3251            .map {
3252                PortScanRowViewData(
3253                    portLabel: "\($0.port)",
3254                    service: $0.service,
3255                    statusLabel: $0.open ? "Open" : "Closed",
3256                    statusTone: $0.open ? .success : .secondary,
3257                    banner: $0.banner,
3258                    durationLabel: $0.durationMs.map { "\($0) ms" }
3259                )
3260            }
3261    }
3262
3263    static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
3264        snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
3265    }
3266
3267    static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
3268        snapshot.redirectChain.last?.url
3269    }
3270
3271    static func httpsSummary(from snapshot: LookupSnapshot) -> String {
3272        if snapshot.sslInfo != nil {
3273            return "Valid"
3274        }
3275        if let sslError = snapshot.sslError {
3276            return sslError.localizedCaseInsensitiveContains("certificate") ? "Invalid" : "Failed"
3277        }
3278        return "Unavailable"
3279    }
3280
3281    private static func httpsSummaryTone(from snapshot: LookupSnapshot) -> ResultTone {
3282        if snapshot.sslInfo != nil {
3283            return .success
3284        }
3285        return snapshot.sslError == nil ? .secondary : .failure
3286    }
3287
3288    static func emailSummary(from snapshot: LookupSnapshot) -> String {
3289        guard let emailSecurity = snapshot.emailSecurity else {
3290            return snapshot.emailSecurityError ?? "Unavailable"
3291        }
3292        return "SPF \(emailSecurity.spf.found ? "Yes" : "No") / DMARC \(emailSecurity.dmarc.found ? "Yes" : "No")"
3293    }
3294
3295    private static func certificateStatusLabel(from snapshot: LookupSnapshot) -> String {
3296        guard let sslInfo = snapshot.sslInfo else {
3297            return snapshot.sslError ?? "Unavailable"
3298        }
3299
3300        switch DomainDiffService.certificateWarningLevel(for: snapshot) {
3301        case .critical:
3302            return "Critical (\(sslInfo.daysUntilExpiry)d)"
3303        case .warning:
3304            return "Warning (\(sslInfo.daysUntilExpiry)d)"
3305        case .none:
3306            return "Healthy (\(sslInfo.daysUntilExpiry)d)"
3307        }
3308    }
3309
3310    private static func certificateBadgeLabel(from snapshot: LookupSnapshot) -> String? {
3311        guard snapshot.sslInfo != nil else { return nil }
3312        return certificateStatusLabel(from: snapshot)
3313    }
3314
3315    private static func certificateStatusTone(from snapshot: LookupSnapshot) -> ResultTone {
3316        guard let daysRemaining = snapshot.sslInfo?.daysUntilExpiry else {
3317            return snapshot.sslError == nil ? .secondary : .failure
3318        }
3319        return certificateTone(daysRemaining: daysRemaining)
3320    }
3321
3322    private static func certificateTone(daysRemaining: Int) -> ResultTone {
3323        if daysRemaining < 14 {
3324            return .failure
3325        }
3326        if daysRemaining < 30 {
3327            return .warning
3328        }
3329        return .success
3330    }
3331
3332    static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
3333        switch status {
3334        case .available:
3335            return "Available"
3336        case .registered:
3337            return "Registered"
3338        case .unknown, .none:
3339            return "Unknown"
3340        }
3341    }
3342
3343    private static func availabilityInference(from snapshot: LookupSnapshot) -> String {
3344        switch snapshot.availabilityResult?.status {
3345        case .registered:
3346            return "Likely registered"
3347        case .available:
3348            return "Possibly available"
3349        case .unknown, .none:
3350            return "Unclear"
3351        }
3352    }
3353
3354    private static func availabilityTone(_ status: DomainAvailabilityStatus?) -> ResultTone {
3355        switch status {
3356        case .available:
3357            return .success
3358        case .registered:
3359            return .warning
3360        case .unknown, .none:
3361            return .secondary
3362        }
3363    }
3364
3365    private static func sourceTone(for snapshot: LookupSnapshot) -> ResultTone {
3366        if snapshot.statusMessage != nil {
3367            return .warning
3368        }
3369
3370        switch snapshot.resultSource {
3371        case .live:
3372            return .success
3373        case .cached:
3374            return .secondary
3375        case .mixed:
3376            return .warning
3377        case .snapshot:
3378            return .warning
3379        }
3380    }
3381
3382    private static func securityGradeTone(_ grade: String) -> ResultTone {
3383        switch grade {
3384        case "A", "B":
3385            return .success
3386        case "C":
3387            return .warning
3388        case "D", "F":
3389            return .failure
3390        default:
3391            return .secondary
3392        }
3393    }
3394
3395    static func durationLabel(_ durationMs: Int?) -> String {
3396        durationMs.map { "\($0) ms" } ?? "Unavailable"
3397    }
3398
3399    private static let certificateDateFormatter: DateFormatter = {
3400        let formatter = DateFormatter()
3401        formatter.dateStyle = .medium
3402        formatter.timeStyle = .short
3403        return formatter
3404    }()
3405
3406    private static let ownershipDateFormatter: DateFormatter = {
3407        let formatter = DateFormatter()
3408        formatter.dateStyle = .medium
3409        formatter.timeStyle = .none
3410        return formatter
3411    }()
3412
3413    private func conciseExternalMessage(_ message: String, fallback: String) -> String {
3414        let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
3415        if trimmed.isEmpty {
3416            return fallback
3417        }
3418        if trimmed.localizedCaseInsensitiveContains("rate") {
3419            return "Rate limited. Try again later."
3420        }
3421        if trimmed.localizedCaseInsensitiveContains("invalid") {
3422            return "External data was invalid."
3423        }
3424        if trimmed.localizedCaseInsensitiveContains("network") {
3425            return "External data is offline."
3426        }
3427        return trimmed
3428    }
3429
3430    private static func isInterestingSubdomain(_ hostname: String) -> Bool {
3431        let keywords = ["admin", "api", "dev", "staging", "test", "internal"]
3432        let labels = hostname.lowercased().split(separator: ".").map(String.init)
3433        return labels.contains { label in
3434            keywords.contains(where: { label.contains($0) })
3435        }
3436    }
3437}
3438