DomainDig/DomainViewModel.swift

3433 lines · 146160 bytes

   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        guard AuditFixtures.requested, !auditFixturesActive else { return }
1797        auditFixturesActive = true
1798        trackedDomains = AuditFixtures.trackedDomains
1799        batchResults = AuditFixtures.batchResults
1800    }
1801    #endif
1802
1803    private func persistTrackedDomains() {
1804        #if DEBUG
1805        if auditFixturesActive { return }
1806        #endif
1807        if trackedDomainsPersistenceSuspended {
1808            trackedDomainsPersistenceDirty = true
1809            return
1810        }
1811        DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
1812        CloudSyncService.shared.scheduleSyncIfNeeded()
1813        refreshDataLifecycleSummary()
1814        refreshWidgetData()
1815    }
1816
1817    private func beginBulkPersistenceDeferral() {
1818        historyPersistenceSuspended = true
1819        trackedDomainsPersistenceSuspended = true
1820        historyPersistenceDirty = false
1821        trackedDomainsPersistenceDirty = false
1822    }
1823
1824    private func endBulkPersistenceDeferral() {
1825        historyPersistenceSuspended = false
1826        trackedDomainsPersistenceSuspended = false
1827
1828        if trackedDomainsPersistenceDirty {
1829            trackedDomainsPersistenceDirty = false
1830            DomainDataPortabilityService.saveTrackedDomains(trackedDomains, defaults: defaults)
1831            CloudSyncService.shared.scheduleSyncIfNeeded()
1832        }
1833
1834        if historyPersistenceDirty {
1835            historyPersistenceDirty = false
1836            DomainDataPortabilityService.saveHistoryEntries(history, defaults: defaults, historyLocation: historyLocation)
1837        }
1838
1839        refreshDataLifecycleSummary()
1840    }
1841
1842    /// What Settings says under the auto-prune picker. The old copy claimed
1843    /// auto-prune "defaults to unlimited", which was never true — there has
1844    /// always been a hard ceiling, and under D1 it is the tier's.
1845    var historyRetentionCaption: String {
1846        let limit = tierHistoryLimit
1847        let base = "History stays on this device. Your plan keeps up to \(limit) snapshots"
1848        guard history.count > limit else {
1849            return base + "; auto-prune trims to fewer if you want."
1850        }
1851        return base
1852            + ", and you have \(history.count). Nothing already saved is removed —"
1853            + " new snapshots replace the oldest instead."
1854    }
1855
1856    /// Snapshots this tier keeps: 50 free, 250 Pro, 2000 Pro+ under D1.
1857    private var tierHistoryLimit: Int {
1858        FeatureAccessService.historyRetentionLimit
1859    }
1860
1861    /// The ceiling a newly stored snapshot is kept under, computed before the
1862    /// insert. Never below what is already held: a lapsed Pro+ subscriber with
1863    /// 2000 snapshots keeps all 2000 (Review Focus #6), and the store holds
1864    /// there rather than draining to the lower tier a row at a time. For
1865    /// anyone at or under their tier's limit this is just that limit.
1866    var growthHistoryLimit: Int {
1867        max(tierHistoryLimit, history.count)
1868    }
1869
1870    /// What the user's own auto-prune choice asks for, which may be less than
1871    /// the tier allows but never more. This one is permitted to delete,
1872    /// because the user chose it.
1873    var requestedHistoryLimit: Int {
1874        min(historyAutoPruneOption.keepCount ?? tierHistoryLimit, tierHistoryLimit)
1875    }
1876
1877    /// Caps growth without pruning what is already stored.
1878    private func trimHistoryToLimit() {
1879        history = Array(history.prefix(growthHistoryLimit))
1880    }
1881
1882    private func nextSnapshotIndex(for domain: String, trackedDomainID: UUID?) -> Int {
1883        let siblings = history.filter { entry in
1884            if let trackedDomainID {
1885                return entry.trackedDomainID == trackedDomainID
1886            }
1887            return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1888        }
1889        let existingMax = siblings.compactMap(\.snapshotIndex).max() ?? siblings.count
1890        return existingMax + 1
1891    }
1892
1893    func persistMonitoringSettings(localActivationConfirmed: Bool = false) {
1894        monitoringSettings = MonitoringStorage.sanitizeSettings(monitoringSettings, trackedDomains: trackedDomains)
1895        MonitoringStorage.saveSettings(monitoringSettings, defaults: defaults)
1896        CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: localActivationConfirmed)
1897    }
1898
1899    func sanitizeMonitoringSelection() {
1900        monitoringSettings = MonitoringStorage.sanitizeSettings(monitoringSettings, trackedDomains: trackedDomains)
1901        MonitoringStorage.saveSettings(monitoringSettings, defaults: defaults)
1902        CloudSyncService.shared.markMonitoringSettingsChanged(localActivationConfirmed: false)
1903    }
1904
1905    private func clearMonitoringLogs() {
1906        monitoringLogs.removeAll()
1907        monitoringStatusMessage = nil
1908        MonitoringStorage.saveLogs([], defaults: defaults)
1909    }
1910
1911    private func updateTrackedDomainAvailability(for domain: String, status: DomainAvailabilityStatus) {
1912        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1913            return
1914        }
1915        trackedDomains[index].lastKnownAvailability = status
1916        persistTrackedDomains()
1917    }
1918
1919    private func updateTrackedDomainSnapshotMetadata(
1920        domain: String,
1921        snapshotID: UUID,
1922        availabilityStatus: DomainAvailabilityStatus?,
1923        updatedAt: Date,
1924        changeSummary: DomainChangeSummary?,
1925        changeSeverity: ChangeSeverity?,
1926        certificateWarningLevel: CertificateWarningLevel,
1927        certificateDaysRemaining: Int?
1928    ) {
1929        guard let index = trackedDomains.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
1930            return
1931        }
1932        trackedDomains[index].lastSnapshotID = snapshotID
1933        trackedDomains[index].lastKnownAvailability = availabilityStatus
1934        trackedDomains[index].updatedAt = updatedAt
1935        trackedDomains[index].lastChangeSummary = changeSummary
1936        trackedDomains[index].lastChangeSeverity = changeSeverity
1937        trackedDomains[index].certificateWarningLevel = certificateWarningLevel
1938        trackedDomains[index].certificateDaysRemaining = certificateDaysRemaining
1939        persistTrackedDomains()
1940    }
1941
1942    private func notifyIfNeeded(for entry: HistoryEntry, snapshot: LookupSnapshot, previousSnapshot: LookupSnapshot?) {
1943        guard notificationsAuthorized, entry.trackedDomainID != nil else { return }
1944
1945        Task {
1946            if let summary = entry.changeSummary, summary.hasChanges {
1947                await LocalNotificationService.shared.notifyDomainEvent(
1948                    domain: entry.domain,
1949                    message: summary.message,
1950                    severity: summary.severity
1951                )
1952            }
1953
1954            let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: snapshot)
1955            if certificateWarningLevel == .critical, let daysRemaining = snapshot.sslInfo?.daysUntilExpiry {
1956                await LocalNotificationService.shared.notifyCertificateWarning(
1957                    domain: entry.domain,
1958                    daysRemaining: daysRemaining
1959                )
1960            }
1961
1962            if let previousStatus = previousSnapshot?.availabilityResult?.status,
1963               let newStatus = snapshot.availabilityResult?.status,
1964               previousStatus != newStatus {
1965                await LocalNotificationService.shared.notifyDomainEvent(
1966                    domain: entry.domain,
1967                    message: "Availability changed",
1968                    severity: .high
1969                )
1970            }
1971        }
1972    }
1973
1974    private func previousSnapshot(for domain: String, trackedDomainID: UUID?, replacingLatest: Bool) -> LookupSnapshot? {
1975        let matchingEntries = history.filter { entry in
1976            if let trackedDomainID {
1977                return entry.trackedDomainID == trackedDomainID
1978            }
1979            return entry.domain.caseInsensitiveCompare(domain) == .orderedSame
1980        }
1981
1982        if replacingLatest {
1983            return matchingEntries.dropFirst().first?.snapshot
1984        }
1985        return matchingEntries.first?.snapshot
1986    }
1987
1988    private func trackedDomain(for domain: String) -> TrackedDomain? {
1989        trackedDomains.first { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }
1990    }
1991
1992    func normalizedDomain(_ domain: String) -> String {
1993        domain
1994            .trimmingCharacters(in: .whitespacesAndNewlines)
1995            .replacingOccurrences(of: "https://", with: "")
1996            .replacingOccurrences(of: "http://", with: "")
1997            .components(separatedBy: "/")
1998            .first?
1999            .lowercased() ?? ""
2000    }
2001
2002    private func linkTrackedDomainHistory(for domain: String) {
2003        guard let trackedDomain = trackedDomain(for: domain) else { return }
2004
2005        var relinked: [HistoryEntry] = []
2006        for index in history.indices where history[index].domain.caseInsensitiveCompare(domain) == .orderedSame {
2007            if history[index].trackedDomainID != trackedDomain.id {
2008                history[index].trackedDomainID = trackedDomain.id
2009                relinked.append(history[index])
2010            }
2011        }
2012
2013        relinked.forEach { updateStoredHistory($0) }
2014
2015        if let latestEntry = history.first(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }),
2016           let trackedIndex = trackedDomains.firstIndex(where: { $0.id == trackedDomain.id }) {
2017            trackedDomains[trackedIndex].lastSnapshotID = latestEntry.id
2018            trackedDomains[trackedIndex].lastChangeSummary = latestEntry.changeSummary
2019            trackedDomains[trackedIndex].lastChangeSeverity = latestEntry.changeSummary?.severity
2020            trackedDomains[trackedIndex].lastKnownAvailability = latestEntry.availabilityResult?.status
2021            trackedDomains[trackedIndex].certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: latestEntry.snapshot)
2022            trackedDomains[trackedIndex].certificateDaysRemaining = latestEntry.sslInfo?.daysUntilExpiry
2023            trackedDomains[trackedIndex].updatedAt = latestEntry.timestamp
2024            persistTrackedDomains()
2025        }
2026    }
2027
2028    func addRecentSearch(_ domain: String) {
2029        recentSearches.removeAll { $0.lowercased() == domain.lowercased() }
2030        recentSearches.insert(domain, at: 0)
2031        if recentSearches.count > Self.maxRecent {
2032            recentSearches = Array(recentSearches.prefix(Self.maxRecent))
2033        }
2034        DomainDataPortabilityService.saveRecentSearches(recentSearches, defaults: defaults)
2035        CloudSyncService.shared.markAppSettingsChanged()
2036        refreshDataLifecycleSummary()
2037    }
2038
2039    func beginLookup(for target: String, cancelExistingTask: Bool = true) -> UUID {
2040        if cancelExistingTask {
2041            lookupTask?.cancel()
2042        }
2043        customPortScanTask?.cancel()
2044
2045        let lookupID = UUID()
2046        activeLookupID = lookupID
2047        lookupStartedAt = Date()
2048        lastLookupDurationMs = nil
2049        addRecentSearch(target)
2050        searchedDomain = target
2051        hasRun = true
2052        currentHistoryEntryID = nil
2053        currentInspectionMetadata = nil
2054        currentSnapshotTimestamp = Date()
2055        currentResultSource = .live
2056        currentCachedSections = []
2057        currentStatusMessage = nil
2058        currentDiffSections = []
2059        currentChangeSummary = nil
2060        currentReport = nil
2061        ownershipDiff = []
2062        clearLookupState()
2063        setAllLoadingStates(true)
2064        return lookupID
2065    }
2066
2067    func startBatchLookup(domains: [String], source: BatchLookupSource, workflow: DomainWorkflow? = nil) {
2068        guard !domains.isEmpty else { return }
2069        guard !batchLookupRunning else { return }
2070
2071        let now = Date()
2072        if let lastBatchStartedAt, now.timeIntervalSince(lastBatchStartedAt) < 1 {
2073            return
2074        }
2075
2076        lastBatchStartedAt = now
2077        clearBatchState()
2078        batchLookupSource = source
2079        activeWorkflowRunID = workflow?.id
2080        activeWorkflowRunName = workflow?.name
2081        batchTotalCount = domains.count
2082        batchLookupRunning = true
2083        batchResults = domains.map {
2084            BatchLookupResult(
2085                domain: $0,
2086                historyEntryID: nil,
2087                availability: nil,
2088                primaryIP: nil,
2089                quickStatus: "Pending",
2090                timestamp: Date(),
2091                status: .pending
2092            )
2093        }
2094
2095        lookupTask?.cancel()
2096        customPortScanTask?.cancel()
2097        batchTask?.cancel()
2098
2099        SweepActivityController.shared.begin(
2100            title: source == .watchlistRefresh ? "Watchlist Sweep" : "Batch Lookup",
2101            total: domains.count
2102        )
2103
2104        batchTask = Task { [weak self] in
2105            guard let self else { return }
2106            self.notificationsAuthorized = await LocalNotificationService.shared.requestAuthorizationIfNeeded()
2107            await self.runBatchLookup(domains: domains, source: source)
2108        }
2109    }
2110
2111    private func clearBatchState() {
2112        batchResults = []
2113        batchLookupSource = .manual
2114        batchCurrentDomain = nil
2115        batchCompletedCount = 0
2116        batchTotalCount = 0
2117        batchLookupRunning = false
2118        latestBatchSweepSummary = nil
2119        latestWorkflowRunSummary = nil
2120        activeBatchDomains = []
2121        activeWorkflowRunID = nil
2122        activeWorkflowRunName = nil
2123        batchTask = nil
2124    }
2125
2126    /// Splits bulk input into the domains that validate and the entries that do
2127    /// not.
2128    ///
2129    /// The rejected entries are returned rather than dropped: they used to go
2130    /// missing silently, so pasting ten domains with two typos ran eight and
2131    /// said nothing about the other two (U5). Before !8 those entries ran and
2132    /// failed visibly per section, and the single-lookup path has reported its
2133    /// own error since — the asymmetry was the defect.
2134    func parsedBulkInput(from input: String) -> ParsedBulkInput {
2135        let separators = CharacterSet(charactersIn: ",").union(.whitespacesAndNewlines)
2136        var seen = Set<String>()
2137        var domains: [String] = []
2138        var skipped: [String] = []
2139
2140        for token in input.components(separatedBy: separators) {
2141            // Whitespace between entries is not an entry.
2142            guard !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { continue }
2143            guard let domain = try? DomainName.validate(token).get() else {
2144                skipped.append(token)
2145                continue
2146            }
2147            if seen.insert(domain).inserted {
2148                domains.append(domain)
2149            }
2150        }
2151
2152        return ParsedBulkInput(domains: domains, skipped: skipped)
2153    }
2154
2155    private func runBatchLookup(domains: [String], source: BatchLookupSource) async {
2156        let concurrencyLimit = min(source == .watchlistRefresh ? 4 : 3, max(domains.count, 1))
2157        var nextIndex = 0
2158        beginBulkPersistenceDeferral()
2159
2160        await withTaskGroup(of: (String, BatchLookupPayload?).self) { group in
2161            for _ in 0..<concurrencyLimit {
2162                guard nextIndex < domains.count else { break }
2163                let domain = domains[nextIndex]
2164                nextIndex += 1
2165                enqueueBatchLookup(domain: domain, source: source, group: &group)
2166            }
2167
2168            while let (domain, payload) = await group.next() {
2169                completeBatchLookup(domain: domain, payload: payload)
2170
2171                if nextIndex < domains.count, !Task.isCancelled {
2172                    let nextDomain = domains[nextIndex]
2173                    nextIndex += 1
2174                    enqueueBatchLookup(domain: nextDomain, source: source, group: &group)
2175                }
2176            }
2177        }
2178
2179        endBulkPersistenceDeferral()
2180        finishBatchLookup(source: source)
2181    }
2182
2183    private func enqueueBatchLookup(
2184        domain: String,
2185        source: BatchLookupSource,
2186        group: inout TaskGroup<(String, BatchLookupPayload?)>
2187    ) {
2188        activeBatchDomains.append(domain)
2189        batchCurrentDomain = activeBatchDomains.first
2190        if source == .watchlistRefresh {
2191            refreshingTrackedDomainID = trackedDomain(for: domain)?.id
2192        }
2193        updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil)
2194        let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false)
2195
2196        group.addTask { [domain, previousSnapshot, scope = InspectionScope.current(defaults: defaults)] in
2197            let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
2198            return (domain, payload)
2199        }
2200    }
2201
2202    private func completeBatchLookup(domain: String, payload: BatchLookupPayload?) {
2203        activeBatchDomains.removeAll { $0.caseInsensitiveCompare(domain) == .orderedSame }
2204        batchCurrentDomain = activeBatchDomains.first
2205
2206        guard let payload else {
2207            updateBatchResult(
2208                domain: domain,
2209                status: .failed,
2210                quickStatus: "Failed",
2211                entry: nil,
2212                resultSource: .live,
2213                errorMessage: "Lookup cancelled"
2214            )
2215            batchCompletedCount += 1
2216            SweepActivityController.shared.update(
2217                completed: batchCompletedCount,
2218                total: batchTotalCount,
2219                currentDomain: batchCurrentDomain
2220            )
2221            return
2222        }
2223
2224        let entry = payload.snapshot.historyEntryID.flatMap { id in
2225            history.first(where: { $0.id == id })
2226        } ?? saveHistoryEntry(from: payload.snapshot, replaceLatest: false, updateCurrentState: false)
2227        let certificateWarningLevel = DomainDiffService.certificateWarningLevel(for: payload.snapshot)
2228        let riskAssessment = entry?.changeSummary?.riskAssessment ?? DomainInsightEngine.analyze(snapshot: payload.snapshot).riskAssessment
2229        let quickStatus: String
2230        if entry?.changeSummary?.hasChanges == true {
2231            if entry?.changeSummary?.impactClassification == .critical {
2232                quickStatus = "Critical"
2233            } else {
2234                quickStatus = entry?.changeSummary?.severity == .high ? "High" : "Changed"
2235            }
2236        } else if certificateWarningLevel != .none {
2237            quickStatus = certificateWarningLevel == .critical ? "Critical" : "Warning"
2238        } else if riskAssessment.level == .high {
2239            quickStatus = "High"
2240        } else {
2241            quickStatus = "Unchanged"
2242        }
2243
2244        updateBatchResult(
2245            domain: domain,
2246            status: .completed,
2247            quickStatus: quickStatus,
2248            entry: entry,
2249            resultSource: payload.snapshot.resultSource,
2250            errorMessage: payload.snapshot.statusMessage
2251        )
2252        batchCompletedCount += 1
2253        SweepActivityController.shared.update(
2254            completed: batchCompletedCount,
2255            total: batchTotalCount,
2256            currentDomain: batchCurrentDomain
2257        )
2258    }
2259
2260    private func finishBatchLookup(source: BatchLookupSource) {
2261        batchLookupRunning = false
2262        batchCurrentDomain = nil
2263        activeBatchDomains = []
2264        refreshingTrackedDomainID = nil
2265        batchTask = nil
2266
2267        let changedCount = batchResults.filter { $0.quickStatus == "Changed" || $0.quickStatus == "High" || $0.quickStatus == "Critical" }.count
2268        let unchangedCount = batchResults.filter { $0.quickStatus == "Unchanged" && $0.status == .completed }.count
2269        let warningCount = batchResults.filter {
2270            $0.certificateWarningLevel != .none
2271                || $0.changeClassification == .warning
2272                || $0.changeClassification == .critical
2273                || $0.riskLevel == .high
2274        }.count
2275
2276        let summary = BatchSweepSummary(
2277            source: source,
2278            totalDomains: batchResults.count,
2279            changedDomains: changedCount,
2280            unchangedDomains: unchangedCount,
2281            warningDomains: warningCount,
2282            results: batchResults.sorted { lhs, rhs in
2283                if lhs.status != rhs.status {
2284                    return lhs.status.rawValue < rhs.status.rawValue
2285                }
2286                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2287            },
2288            generatedAt: Date()
2289        )
2290        latestBatchSweepSummary = summary
2291        // Only the domains that actually completed: a failed lookup has no
2292        // report to upload.
2293        IntegrationService.shared.enqueueExports(
2294            domains: batchResults.filter { $0.status == .completed }.map(\.domain),
2295            trigger: .batch
2296        )
2297        SweepActivityController.shared.end(changed: changedCount, warnings: warningCount)
2298        AppAccessibility.announce(
2299            "Sweep complete. \(summary.results.count) domains, \(changedCount) changed, \(warningCount) warnings."
2300        )
2301
2302        if source == .workflow, let activeWorkflowRunID, let activeWorkflowRunName {
2303            let workflowReports: [DomainReport] = summary.results.compactMap { result in
2304                guard let entry = historyEntry(for: result) else { return nil }
2305                return report(for: entry)
2306            }
2307            latestWorkflowRunSummary = WorkflowRunSummary(
2308                workflowID: activeWorkflowRunID,
2309                workflowName: activeWorkflowRunName,
2310                totalDomains: batchResults.count,
2311                changedDomains: changedCount,
2312                unchangedDomains: unchangedCount,
2313                warningDomains: warningCount,
2314                results: summary.results,
2315                workflowInsights: DomainInsightEngine.workflowInsights(for: workflowReports),
2316                generatedAt: summary.generatedAt
2317            )
2318        }
2319
2320        if notificationsAuthorized, source != .workflow {
2321            Task {
2322                await LocalNotificationService.shared.notifySweepComplete(summary: summary)
2323            }
2324        }
2325    }
2326
2327    private func updateBatchResult(
2328        domain: String,
2329        status: BatchLookupStatus,
2330        quickStatus: String,
2331        entry: HistoryEntry?,
2332        resultSource: LookupResultSource = .live,
2333        errorMessage: String?
2334    ) {
2335        guard let index = batchResults.firstIndex(where: { $0.domain.caseInsensitiveCompare(domain) == .orderedSame }) else {
2336            return
2337        }
2338
2339        batchResults[index] = BatchLookupResult(
2340            id: batchResults[index].id,
2341            domain: domain,
2342            historyEntryID: entry?.id,
2343            resultSource: resultSource,
2344            availability: entry?.availabilityResult?.status,
2345            primaryIP: entry?.primaryIP,
2346            quickStatus: quickStatus,
2347            summaryMessage: entry?.changeSummary?.message,
2348            changeSeverity: entry?.changeSummary?.severity,
2349            changeClassification: entry?.changeSummary?.impactClassification,
2350            certificateWarningLevel: entry.map { DomainDiffService.certificateWarningLevel(for: $0.snapshot) } ?? batchResults[index].certificateWarningLevel,
2351            riskScore: entry.map { $0.changeSummary?.riskAssessment?.score ?? report(for: $0).riskAssessment.score },
2352            riskLevel: entry.map { $0.changeSummary?.riskAssessment?.level ?? report(for: $0).riskAssessment.level },
2353            timestamp: entry?.timestamp ?? Date(),
2354            status: status,
2355            errorMessage: errorMessage
2356        )
2357    }
2358
2359    /// Resets every section before a new lookup, so the previous domain's
2360    /// results cannot be mistaken for this one's. One assignment per section
2361    /// now; it used to be three.
2362    private func clearLookupState() {
2363        currentInspectionMetadata = nil
2364        dnsState = .idle
2365        availabilityState = .idle
2366        suggestionsState = .idle
2367        sslState = .idle
2368        hstsState = .idle
2369        httpHeadersState = .idle
2370        httpSecurityGrade = nil
2371        httpStatusCode = nil
2372        httpResponseTimeMs = nil
2373        httpProtocol = nil
2374        http3Advertised = false
2375        reachabilityState = .idle
2376        ipGeolocationState = .idle
2377        emailSecurityState = .idle
2378        ownershipState = .idle
2379        ownershipHistoryState = .idle
2380        ptrState = .idle
2381        redirectChainState = .idle
2382        subdomainsState = .idle
2383        extendedSubdomainsState = .idle
2384        dnsHistoryState = .idle
2385        domainPricingState = .idle
2386        reputationState = .idle
2387        portScanState = .idle
2388        customPortScanState = .idle
2389    }
2390
2391    /// Puts the sections a lookup drives into flight, and resets the
2392    /// on-demand ones — ownership history, extended subdomains, DNS history
2393    /// and pricing are fetched when the user opens them, not by the lookup, so
2394    /// they were never part of this either.
2395    private func setAllLoadingStates(_ loading: Bool) {
2396        let phase: SectionPhase = loading ? .loading : .idle
2397        dnsState.phase = phase
2398        availabilityState.phase = phase
2399        suggestionsState.phase = phase
2400        sslState.phase = phase
2401        hstsState.phase = phase
2402        httpHeadersState.phase = phase
2403        reachabilityState.phase = phase
2404        ipGeolocationState.phase = phase
2405        emailSecurityState.phase = phase
2406        ownershipState.phase = phase
2407        ptrState.phase = phase
2408        redirectChainState.phase = phase
2409        subdomainsState.phase = phase
2410        portScanState.phase = phase
2411
2412        ownershipHistoryState.phase = .idle
2413        extendedSubdomainsState.phase = .idle
2414        dnsHistoryState.phase = .idle
2415        domainPricingState.phase = .idle
2416    }
2417
2418    private func primaryIPAddress(from sections: [DNSSection]) -> String? {
2419        sections.first(where: { $0.recordType == .A })?.records.first?.value
2420    }
2421
2422    func isCurrentLookup(_ lookupID: UUID) -> Bool {
2423        activeLookupID == lookupID
2424    }
2425
2426    func recentSnapshots(for trackedDomain: TrackedDomain, limit: Int = 6) -> [HistoryEntry] {
2427        history
2428            .filter { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
2429            .sorted { $0.timestamp > $1.timestamp }
2430            .prefix(limit)
2431            .map { $0 }
2432    }
2433
2434    func latestSnapshots(for domains: [TrackedDomain]) -> [HistoryEntry] {
2435        domains.compactMap { trackedDomain in
2436            recentSnapshots(for: trackedDomain, limit: 1).first
2437        }
2438    }
2439
2440    func diffSectionsForLatestSnapshots(of trackedDomain: TrackedDomain) -> [DomainDiffSection] {
2441        let snapshots = recentSnapshots(for: trackedDomain, limit: 2)
2442        guard snapshots.count == 2 else { return [] }
2443        return DomainDiffService.diff(from: snapshots[1].snapshot, to: snapshots[0].snapshot)
2444    }
2445
2446    func latestChangeSummary(for trackedDomain: TrackedDomain) -> DomainChangeSummary? {
2447        trackedDomain.lastChangeSummary ?? recentSnapshots(for: trackedDomain, limit: 1).first?.changeSummary
2448    }
2449
2450    func latestSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot? {
2451        recentSnapshots(for: trackedDomain, limit: 1).first?.snapshot
2452    }
2453
2454    func trackedDomain(withID id: UUID) -> TrackedDomain? {
2455        trackedDomains.first(where: { $0.id == id })
2456    }
2457
2458    private func buildPortfolioDomainStates() -> [PortfolioDomainStatus] {
2459        let now = Date()
2460        return sortedTrackedDomains(from: trackedDomains, using: .pinned).map { trackedDomain in
2461            let recentEntries = recentSnapshots(for: trackedDomain, limit: 8)
2462            let latestEntry = recentEntries.first
2463            let report = latestEntry.map { self.report(for: $0) } ?? reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
2464            let recentMonitoringResults = monitoringLogs
2465                .flatMap(\.checkedDomains)
2466                .filter { $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }
2467                .sorted { $0.checkedAt > $1.checkedAt }
2468            let recentFailureResults = recentMonitoringResults.filter {
2469                let isFailure = $0.errorMessage != nil || ($0.alertSeverity ?? .info) >= .warning
2470                return isFailure && now.timeIntervalSince($0.checkedAt) <= 7 * 24 * 60 * 60
2471            }
2472            let recentChangeCount = recentEntries.filter {
2473                guard let changeSummary = $0.changeSummary, changeSummary.hasChanges else { return false }
2474                return now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2475            }.count
2476            let recentDNSChange = recentEntries.contains {
2477                guard let changeSummary = $0.changeSummary else { return false }
2478                return changeSummary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") })
2479                    && now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2480            }
2481            let recentCriticalChange = recentEntries.contains {
2482                guard let changeSummary = $0.changeSummary else { return false }
2483                return changeSummary.impactClassification == .critical
2484                    && now.timeIntervalSince($0.timestamp) <= 7 * 24 * 60 * 60
2485            }
2486            let certificateExpiryState = trackedDomain.certificateWarningLevel == .none
2487                ? report.certificateExpiryState
2488                : trackedDomain.certificateWarningLevel
2489            let isUnreachable: Bool = {
2490                if let latestEntry {
2491                    if !latestEntry.reachabilityResults.isEmpty {
2492                        return !latestEntry.reachabilityResults.contains(where: \.reachable)
2493                    }
2494                    if latestEntry.reachabilityError != nil {
2495                        return true
2496                    }
2497                }
2498                return recentFailureResults.contains { ($0.alertSeverity ?? .info) == .critical && $0.errorMessage != nil }
2499            }()
2500            let hasInvalidTLS = latestEntry?.sslInfo == nil && latestEntry?.sslError != nil
2501            let instabilityScore = DomainHealth.instabilityScore(
2502                recentChangeCount: recentChangeCount,
2503                recentFailureCount: recentFailureResults.count,
2504                pendingAlertCount: trackedDomain.pendingMonitoringAlerts.count,
2505                hasRecentDNSChange: recentDNSChange
2506            )
2507            let health = DomainHealth.classify(
2508                certificateExpiryState: certificateExpiryState,
2509                isReachable: !isUnreachable,
2510                recentMonitoringFailureCount: recentFailureResults.count,
2511                hasRecentDNSChange: recentDNSChange,
2512                instabilityScore: instabilityScore,
2513                hasRecentCriticalChange: recentCriticalChange,
2514                hasInvalidTLS: hasInvalidTLS
2515            )
2516
2517            return PortfolioDomainStatus(
2518                trackedDomain: trackedDomain,
2519                latestEntry: latestEntry,
2520                report: report,
2521                apexDomain: apexDomain(for: trackedDomain.domain),
2522                health: health,
2523                lastChangeDate: latestEntry?.changeSummary?.hasChanges == true
2524                    ? latestEntry?.timestamp
2525                    : trackedDomain.monitoringState.lastChangeDate ?? report.lastChangeDate,
2526                lastMonitoringFailure: recentFailureResults.first?.checkedAt,
2527                instabilityScore: instabilityScore,
2528                certificateExpiryState: certificateExpiryState,
2529                certificateDaysRemaining: trackedDomain.certificateDaysRemaining ?? latestEntry?.sslInfo?.daysUntilExpiry,
2530                isUnreachable: isUnreachable,
2531                recentDNSChange: recentDNSChange,
2532                recentCriticalChange: recentCriticalChange,
2533                recentFailureCount: recentFailureResults.count
2534            )
2535        }
2536    }
2537
2538    private func buildPortfolioActivity(from domainStates: [PortfolioDomainStatus]) -> [PortfolioActivityItem] {
2539        var items: [PortfolioActivityItem] = []
2540        let healthByDomainID = Dictionary(uniqueKeysWithValues: domainStates.map { ($0.trackedDomain.id, $0.health) })
2541
2542        for state in domainStates {
2543            if let latestEntry = state.latestEntry,
2544               let changeSummary = latestEntry.changeSummary,
2545               changeSummary.hasChanges {
2546                items.append(
2547                    PortfolioActivityItem(
2548                        id: "history|\(latestEntry.id.uuidString)",
2549                        trackedDomainID: state.trackedDomain.id,
2550                        domain: state.trackedDomain.domain,
2551                        message: portfolioHistoryMessage(for: latestEntry),
2552                        timestamp: latestEntry.timestamp,
2553                        health: state.health,
2554                        systemImage: portfolioHistoryIcon(for: latestEntry)
2555                    )
2556                )
2557            }
2558        }
2559
2560        for log in monitoringLogs.prefix(25) {
2561            for result in log.checkedDomains where result.didChange || result.errorMessage != nil || result.certificateWarningLevel != .none {
2562                guard let trackedDomain = trackedDomain(for: result.domain) else { continue }
2563                items.append(
2564                    PortfolioActivityItem(
2565                        id: "monitoring|\(log.id.uuidString)|\(result.id.uuidString)",
2566                        trackedDomainID: trackedDomain.id,
2567                        domain: trackedDomain.domain,
2568                        message: portfolioMonitoringMessage(for: result),
2569                        timestamp: result.checkedAt,
2570                        health: healthByDomainID[trackedDomain.id] ?? (result.alertSeverity == .critical ? .critical : .warning),
2571                        systemImage: portfolioMonitoringIcon(for: result)
2572                    )
2573                )
2574            }
2575        }
2576
2577        var seen = Set<String>()
2578        return items
2579            .sorted { $0.timestamp > $1.timestamp }
2580            .filter { item in
2581                let key = "\(item.domain.lowercased())|\(item.message.lowercased())"
2582                return seen.insert(key).inserted
2583            }
2584    }
2585
2586    private func buildAttentionQueue(from domainStates: [PortfolioDomainStatus]) -> [PortfolioAttentionItem] {
2587        domainStates.compactMap { state in
2588            guard state.health != .healthy else { return nil }
2589            let (reason, timestamp) = Self.attentionReason(for: state)
2590            return PortfolioAttentionItem(
2591                id: "\(state.trackedDomain.id.uuidString)|\(reason)",
2592                trackedDomainID: state.trackedDomain.id,
2593                domain: state.trackedDomain.domain,
2594                reason: reason,
2595                timestamp: timestamp,
2596                health: state.health
2597            )
2598        }
2599        .sorted { lhs, rhs in
2600            if lhs.health != rhs.health {
2601                return lhs.health.severityRank > rhs.health.severityRank
2602            }
2603            return lhs.timestamp > rhs.timestamp
2604        }
2605    }
2606
2607    /// Why an unhealthy domain needs attention, most urgent cause first, and
2608    /// when that cause was last seen.
2609    private static func attentionReason(for state: PortfolioDomainStatus) -> (reason: String, timestamp: Date) {
2610        let changedAt = state.lastChangeDate ?? state.trackedDomain.updatedAt
2611        let failedAt = state.lastMonitoringFailure ?? state.trackedDomain.updatedAt
2612        if state.isUnreachable {
2613            return ("Endpoint is unreachable", failedAt)
2614        }
2615        if state.certificateExpiryState == .critical {
2616            return ("Certificate is expiring in under 14 days", changedAt)
2617        }
2618        if state.certificateExpiryState == .warning {
2619            return ("Certificate expires within 30 days", changedAt)
2620        }
2621        if state.recentFailureCount >= 2 || state.instabilityScore >= 70 {
2622            return ("Repeated instability detected", failedAt)
2623        }
2624        if state.recentDNSChange {
2625            return ("DNS changed recently", changedAt)
2626        }
2627        if state.recentCriticalChange {
2628            return ("Recent critical change detected", changedAt)
2629        }
2630        return ("Needs attention", state.trackedDomain.updatedAt)
2631    }
2632
2633    private func portfolioHistoryMessage(for entry: HistoryEntry) -> String {
2634        guard let summary = entry.changeSummary else {
2635            return "Configuration changed for \(entry.domain)"
2636        }
2637        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") }) {
2638            return "DNS changed for \(entry.domain)"
2639        }
2640        if summary.changedSections.contains(where: {
2641            $0.localizedCaseInsensitiveContains("certificate")
2642                || $0.localizedCaseInsensitiveContains("tls")
2643        }) {
2644            return "Certificate updated for \(entry.domain)"
2645        }
2646        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("redirect") }) {
2647            return "Redirect chain changed for \(entry.domain)"
2648        }
2649        return summary.message
2650    }
2651
2652    private func portfolioHistoryIcon(for entry: HistoryEntry) -> String {
2653        guard let summary = entry.changeSummary else { return "clock.arrow.trianglehead.counterclockwise.rotate.90" }
2654        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("dns") }) {
2655            return "point.3.connected.trianglepath.dotted"
2656        }
2657        if summary.changedSections.contains(where: {
2658            $0.localizedCaseInsensitiveContains("certificate")
2659                || $0.localizedCaseInsensitiveContains("tls")
2660        }) {
2661            return "lock.rotation"
2662        }
2663        if summary.changedSections.contains(where: { $0.localizedCaseInsensitiveContains("redirect") }) {
2664            return "arrow.triangle.branch"
2665        }
2666        return "clock.arrow.trianglehead.counterclockwise.rotate.90"
2667    }
2668
2669    private func portfolioMonitoringMessage(for result: MonitoringDomainResult) -> String {
2670        if result.errorMessage != nil {
2671            return "Monitoring failed for \(result.domain)"
2672        }
2673        if result.certificateWarningLevel != .none {
2674            return "Certificate needs attention for \(result.domain)"
2675        }
2676        if result.didChange {
2677            return result.summaryMessage.isEmpty ? "Monitoring detected a change for \(result.domain)" : result.summaryMessage
2678        }
2679        return "Monitoring updated \(result.domain)"
2680    }
2681
2682    private func portfolioMonitoringIcon(for result: MonitoringDomainResult) -> String {
2683        if result.errorMessage != nil {
2684            return "xmark.octagon.fill"
2685        }
2686        if result.certificateWarningLevel != .none {
2687            return "exclamationmark.triangle.fill"
2688        }
2689        return "waveform.path.ecg"
2690    }
2691
2692    private func apexDomain(for domain: String) -> String {
2693        let parts = domain
2694            .lowercased()
2695            .split(separator: ".")
2696            .map(String.init)
2697        guard parts.count > 2 else { return domain.lowercased() }
2698        return parts.suffix(2).joined(separator: ".")
2699    }
2700
2701    private func exportSnapshots(for domains: [TrackedDomain]) -> [LookupSnapshot] {
2702        let latestEntries = latestSnapshots(for: domains)
2703
2704        return domains.map { trackedDomain in
2705            if let entry = latestEntries.first(where: { $0.trackedDomainID == trackedDomain.id || $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame }) {
2706                return entry.snapshot
2707            }
2708            return placeholderSnapshot(for: trackedDomain)
2709        }
2710    }
2711
2712    func currentBatchReports() -> [DomainReport] {
2713        currentBatchResultEntries.map { entry in
2714            report(for: entry, workflowContext: activeWorkflowContext)
2715        }
2716    }
2717
2718    func workflowReports(from summary: WorkflowRunSummary, changedOnly: Bool) -> [DomainReport] {
2719        let filteredResults = changedOnly ? summary.results.filter(\.hasMeaningfulChange) : summary.results
2720        return filteredResults.compactMap { result in
2721            guard let entry = historyEntry(for: result) else { return nil }
2722            return report(
2723                for: entry,
2724                workflowContext: DomainWorkflowContext(
2725                    workflowID: summary.workflowID,
2726                    workflowName: summary.workflowName,
2727                    source: "workflow"
2728                )
2729            )
2730        }
2731    }
2732
2733    func reports(for domains: [TrackedDomain]) -> [DomainReport] {
2734        let latestEntries = latestSnapshots(for: domains)
2735
2736        return domains.map { trackedDomain in
2737            if let entry = latestEntries.first(where: {
2738                $0.trackedDomainID == trackedDomain.id ||
2739                $0.domain.caseInsensitiveCompare(trackedDomain.domain) == .orderedSame
2740            }) {
2741                return report(for: entry)
2742            }
2743
2744            return reportBuilder.build(from: placeholderSnapshot(for: trackedDomain))
2745        }
2746    }
2747
2748    func timelineReports(for domain: String) -> [DomainReport] {
2749        historyEntries(for: domain).map { report(for: $0) }
2750    }
2751
2752    private func report(for entry: HistoryEntry, workflowContext: DomainWorkflowContext? = nil) -> DomainReport {
2753        reportBuilder.build(
2754            from: entry,
2755            previousSnapshot: comparisonSnapshot(for: entry),
2756            workflowContext: workflowContext,
2757            historyEntries: historyEntries(for: entry.domain)
2758        )
2759    }
2760
2761    private var activeWorkflowContext: DomainWorkflowContext? {
2762        guard batchLookupSource == .workflow, let activeWorkflowRunID, let activeWorkflowRunName else {
2763            return nil
2764        }
2765        return DomainWorkflowContext(
2766            workflowID: activeWorkflowRunID,
2767            workflowName: activeWorkflowRunName,
2768            source: "workflow"
2769        )
2770    }
2771
2772    private static var defaultAuditReviewer: String {
2773        let reviewer = NSFullUserName().trimmingCharacters(in: .whitespacesAndNewlines)
2774        return reviewer.isEmpty ? "Local Reviewer" : reviewer
2775    }
2776
2777    private func snapshotEvidenceAssets(from report: DomainReport) -> [AuditEvidenceAsset] {
2778        var assets: [AuditEvidenceAsset] = []
2779        if let finalURL = report.web.finalURL {
2780            assets.append(AuditEvidenceAsset(title: "Final URL", kind: .document, reference: finalURL))
2781        }
2782        if let registrar = report.ownership?.registrar {
2783            assets.append(AuditEvidenceAsset(title: "Registrar", kind: .document, reference: registrar))
2784        }
2785        if let primaryIP = report.dns.primaryIP {
2786            assets.append(AuditEvidenceAsset(title: "Primary IP", kind: .document, reference: primaryIP))
2787        }
2788        if !report.web.redirectChain.isEmpty {
2789            assets.append(
2790                AuditEvidenceAsset(
2791                    title: "Redirect Chain",
2792                    kind: .document,
2793                    reference: report.web.redirectChain.map { "\($0.statusCode) \($0.url)" }.joined(separator: " | ")
2794                )
2795            )
2796        }
2797        if !report.web.headers.isEmpty {
2798            assets.append(
2799                AuditEvidenceAsset(
2800                    title: "Observed Headers",
2801                    kind: .document,
2802                    reference: report.web.headers.prefix(6).map { "\($0.name): \($0.value)" }.joined(separator: " | ")
2803                )
2804            )
2805        }
2806        return assets
2807    }
2808
2809    private func placeholderSnapshot(for trackedDomain: TrackedDomain) -> LookupSnapshot {
2810        LookupSnapshot(
2811            historyEntryID: trackedDomain.lastSnapshotID,
2812            domain: trackedDomain.domain,
2813            timestamp: trackedDomain.updatedAt,
2814            trackedDomainID: trackedDomain.id,
2815            note: trackedDomain.note,
2816            appVersion: AppVersion.current,
2817            resolverDisplayName: resolverDisplayName,
2818            resolverURLString: resolverURLString,
2819            dataSources: [],
2820            provenanceBySection: [:],
2821            availabilityConfidence: nil,
2822            ownershipConfidence: nil,
2823            subdomainConfidence: nil,
2824            emailSecurityConfidence: nil,
2825            geolocationConfidence: nil,
2826            errorDetails: [:],
2827            isPartialSnapshot: true,
2828            validationIssues: ["No stored snapshot data available"],
2829            totalLookupDurationMs: nil,
2830            snapshotIndex: nil,
2831            previousSnapshotID: nil,
2832            changeCount: 0,
2833            severitySummary: trackedDomain.lastChangeSeverity,
2834            dnsSections: [],
2835            dnsError: nil,
2836            availabilityResult: DomainAvailabilityResult(domain: trackedDomain.domain, status: trackedDomain.lastKnownAvailability ?? .unknown),
2837            suggestions: [],
2838            sslInfo: nil,
2839            sslError: nil,
2840            hstsPreloaded: nil,
2841            httpHeaders: [],
2842            httpSecurityGrade: nil,
2843            httpStatusCode: nil,
2844            httpResponseTimeMs: nil,
2845            httpProtocol: nil,
2846            http3Advertised: false,
2847            httpHeadersError: nil,
2848            reachabilityResults: [],
2849            reachabilityError: nil,
2850            ipGeolocation: nil,
2851            ipGeolocationError: nil,
2852            emailSecurity: nil,
2853            emailSecurityError: nil,
2854            ownership: nil,
2855            ownershipError: nil,
2856            ownershipHistory: [],
2857            ownershipHistoryError: nil,
2858            inferredProvider: nil,
2859            priorProviders: [],
2860            domainClassification: nil,
2861            ownershipTransitions: [],
2862            hostingTransitions: [],
2863            subdomainHistory: [],
2864            riskSignals: [],
2865            intelligenceTimeline: [],
2866            ptrRecord: nil,
2867            ptrError: nil,
2868            redirectChain: [],
2869            redirectChainError: nil,
2870            subdomains: [],
2871            subdomainsError: nil,
2872            extendedSubdomains: [],
2873            extendedSubdomainsError: nil,
2874            dnsHistory: [],
2875            dnsHistoryError: nil,
2876            domainPricing: nil,
2877            domainPricingError: nil,
2878            reputation: nil,
2879            reputationError: nil,
2880            portScanResults: [],
2881            portScanError: nil,
2882            changeSummary: trackedDomain.lastChangeSummary,
2883            resultSource: .snapshot,
2884            cachedSections: [],
2885            statusMessage: nil
2886        )
2887    }
2888
2889    private static func loadHistoryEntries(
2890        defaults: UserDefaults,
2891        historyLocation: HistoryFileStore.Location
2892    ) -> [HistoryEntry] {
2893        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2894        return DomainDataPortabilityService.loadHistoryEntries(
2895            defaults: defaults,
2896            historyLocation: historyLocation
2897        )
2898    }
2899
2900    private static func loadHistoryAutoPruneOption(defaults: UserDefaults) -> HistoryAutoPruneOption {
2901        guard let rawValue = defaults.string(forKey: historyAutoPruneKey),
2902              let option = HistoryAutoPruneOption(rawValue: rawValue) else {
2903            return .unlimited
2904        }
2905        return option
2906    }
2907
2908    private static func loadTrackedDomains(
2909        defaults: UserDefaults,
2910        historyLocation: HistoryFileStore.Location
2911    ) -> [TrackedDomain] {
2912        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2913        return DomainDataPortabilityService.loadTrackedDomains(defaults: defaults)
2914    }
2915
2916    func persistWorkflows() {
2917        DomainDataPortabilityService.saveWorkflows(workflows, defaults: defaults)
2918        CloudSyncService.shared.scheduleSyncIfNeeded()
2919        refreshDataLifecycleSummary()
2920    }
2921
2922    static func loadWorkflows(
2923        defaults: UserDefaults,
2924        historyLocation: HistoryFileStore.Location
2925    ) -> [DomainWorkflow] {
2926        DataMigrationService.migrateIfNeeded(defaults: defaults, historyLocation: historyLocation)
2927        return DomainDataPortabilityService.loadWorkflows(defaults: defaults)
2928    }
2929
2930    private static func deduplicatedTrackedDomains(_ domains: [TrackedDomain]) -> [TrackedDomain] {
2931        var seen = Set<String>()
2932        return domains.filter { domain in
2933            let key = domain.domain.lowercased()
2934            return seen.insert(key).inserted
2935        }
2936    }
2937
2938    func normalizedDomains(_ domains: [String]) -> [String] {
2939        var seen = Set<String>()
2940        return domains
2941            .map(normalizedDomain)
2942            .filter { !$0.isEmpty }
2943            .filter { seen.insert($0).inserted }
2944    }
2945
2946    private func historySortPredicate(lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
2947        switch historySortOption {
2948        case .newest:
2949            return lhs.timestamp > rhs.timestamp
2950        case .oldest:
2951            return lhs.timestamp < rhs.timestamp
2952        case .domain:
2953            let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
2954            if domainOrder != .orderedSame {
2955                return domainOrder == .orderedAscending
2956            }
2957            return lhs.timestamp > rhs.timestamp
2958        }
2959    }
2960
2961    private func sortedTrackedDomains(from domains: [TrackedDomain], using sortOption: WatchlistSortOption) -> [TrackedDomain] {
2962        domains.sorted { lhs, rhs in
2963            switch sortOption {
2964            case .pinned:
2965                if lhs.isPinned != rhs.isPinned {
2966                    return lhs.isPinned && !rhs.isPinned
2967                }
2968                if lhs.updatedAt != rhs.updatedAt {
2969                    return lhs.updatedAt > rhs.updatedAt
2970                }
2971                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2972            case .recentlyUpdated:
2973                if lhs.updatedAt != rhs.updatedAt {
2974                    return lhs.updatedAt > rhs.updatedAt
2975                }
2976                return lhs.domain.localizedCaseInsensitiveCompare(rhs.domain) == .orderedAscending
2977            case .alphabetical:
2978                let domainOrder = lhs.domain.localizedCaseInsensitiveCompare(rhs.domain)
2979                if domainOrder != .orderedSame {
2980                    return domainOrder == .orderedAscending
2981                }
2982                return lhs.updatedAt > rhs.updatedAt
2983            }
2984        }
2985    }
2986
2987    static func summaryFields(from snapshot: LookupSnapshot) -> [SummaryFieldViewData] {
2988        [
2989            SummaryFieldViewData(label: "Domain", value: snapshot.domain.nilIfEmpty ?? "Unavailable", tone: .primary),
2990            SummaryFieldViewData(label: "Observed IP", value: primaryIPAddress(from: snapshot) ?? "Unavailable", tone: .primary),
2991            SummaryFieldViewData(label: "Observed Redirect", value: finalRedirectTarget(from: snapshot) ?? "Unavailable", tone: .secondary),
2992            SummaryFieldViewData(label: "Inference", value: availabilityInference(from: snapshot), tone: availabilityTone(snapshot.availabilityResult?.status)),
2993            SummaryFieldViewData(label: "Observed TLS", value: httpsSummary(from: snapshot), tone: httpsSummaryTone(from: snapshot)),
2994            SummaryFieldViewData(label: "Certificate", value: certificateStatusLabel(from: snapshot), tone: certificateStatusTone(from: snapshot)),
2995            SummaryFieldViewData(label: "Source", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot))
2996        ]
2997    }
2998
2999    static func domainRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3000        var rows = [
3001            InfoRowViewData(label: "Domain", value: snapshot.domain, tone: .primary),
3002            InfoRowViewData(label: "Resolver", value: snapshot.resolverDisplayName, tone: .secondary),
3003            InfoRowViewData(label: "Collected", value: snapshot.timestamp.formatted(date: .abbreviated, time: .shortened), tone: .secondary),
3004            InfoRowViewData(label: snapshot.statusMessage == nil ? "Result" : "Snapshot", value: snapshot.statusMessage ?? snapshot.resultSource.label, tone: sourceTone(for: snapshot)),
3005            InfoRowViewData(label: "Lookup Duration", value: durationLabel(snapshot.totalLookupDurationMs), tone: .secondary)
3006        ]
3007        rows.insert(
3008            InfoRowViewData(
3009                label: "Observed Availability",
3010                value: snapshot.availabilityResult?.status == .unknown ? "No direct registration proof" : "Status collected",
3011                tone: .secondary
3012            ),
3013            at: 1
3014        )
3015        rows.insert(
3016            InfoRowViewData(
3017                label: "Inference",
3018                value: availabilityInference(from: snapshot),
3019                tone: availabilityTone(snapshot.availabilityResult?.status)
3020            ),
3021            at: 2
3022        )
3023        if let confidence = snapshot.availabilityConfidence {
3024            rows.insert(
3025                InfoRowViewData(label: "Confidence", value: confidence.title, tone: .secondary),
3026                at: 3
3027            )
3028        }
3029        if let pricing = snapshot.domainPricing {
3030            rows += pricingRows(pricing)
3031        }
3032        if let reputation = snapshot.reputation {
3033            rows.append(reputationRow(reputation))
3034        }
3035        if let certificateStatus = certificateBadgeLabel(from: snapshot) {
3036            rows.insert(
3037                InfoRowViewData(
3038                    label: "Certificate",
3039                    value: certificateStatus,
3040                    tone: certificateStatusTone(from: snapshot)
3041                ),
3042                at: 2
3043            )
3044        }
3045        return rows
3046    }
3047
3048    private static func pricingRows(_ pricing: DomainPricingInsight) -> [InfoRowViewData] {
3049        var rows = [InfoRowViewData(label: "External Price", value: pricing.estimatedPrice ?? "Unavailable", tone: .secondary)]
3050        if let premiumIndicator = pricing.premiumIndicator {
3051            rows.append(
3052                InfoRowViewData(
3053                    label: "Premium",
3054                    value: premiumIndicator ? "Yes" : "No",
3055                    tone: premiumIndicator ? .warning : .secondary
3056                )
3057            )
3058        }
3059        if let resaleSignal = pricing.resaleSignal {
3060            rows.append(InfoRowViewData(label: "Resale", value: resaleSignal, tone: .secondary))
3061        }
3062        if let auctionSignal = pricing.auctionSignal {
3063            rows.append(InfoRowViewData(label: "Auction", value: auctionSignal, tone: .secondary))
3064        }
3065        return rows
3066    }
3067
3068    private static func reputationRow(_ reputation: DomainReputationResult) -> InfoRowViewData {
3069        let tone: ResultTone
3070        switch reputation.status {
3071        case .clean: tone = .success
3072        case .listed: tone = .failure
3073        case .unknown: tone = .secondary
3074        }
3075        let value = reputation.status == .listed && !reputation.listedSources.isEmpty
3076            ? "\(reputation.status.title) (\(reputation.listedSources.joined(separator: ", ")))"
3077            : reputation.status.title
3078        return InfoRowViewData(label: "Reputation", value: value, tone: tone)
3079    }
3080
3081    static func suggestionRows(from snapshot: LookupSnapshot) -> [DomainSuggestionViewData] {
3082        snapshot.suggestions.map {
3083            DomainSuggestionViewData(
3084                id: $0.id,
3085                domain: $0.domain,
3086                availabilityStatus: $0.status,
3087                status: availabilityLabel($0.status),
3088                tone: availabilityTone($0.status)
3089            )
3090        }
3091    }
3092
3093    static func subdomainRows(from subdomains: [DiscoveredSubdomain]) -> [SubdomainRowViewData] {
3094        subdomains.map { subdomain in
3095            SubdomainRowViewData(
3096                hostname: subdomain.hostname,
3097                isInteresting: subdomain.isExtended || isInterestingSubdomain(subdomain.hostname)
3098            )
3099        }
3100    }
3101
3102    static func dnsRows(from snapshot: LookupSnapshot) -> [DNSRecordSectionViewData] {
3103        snapshot.dnsSections.map { section in
3104            DNSRecordSectionViewData(
3105                title: section.recordType.rawValue,
3106                rows: section.records.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary, speechStyle: .technical) },
3107                wildcardRows: section.wildcardRecords.map { InfoRowViewData(label: "TTL \($0.ttl)", value: $0.value, tone: .primary, speechStyle: .technical) },
3108                wildcardTitle: section.wildcardRecords.isEmpty ? nil : "*.\(snapshot.domain)",
3109                message: section.error.map { SectionMessageViewData(text: $0, isError: true) } ??
3110                    ((section.records.isEmpty && section.wildcardRecords.isEmpty) ? SectionMessageViewData(text: "No records found", isError: false) : nil)
3111            )
3112        }
3113    }
3114
3115    static func dnssecLabel(from snapshot: LookupSnapshot) -> String? {
3116        guard let signed = snapshot.dnsSections.compactMap(\.dnssecSigned).first else { return nil }
3117        return "Resolver-reported DNSSEC (not full validation): \(signed ? "Yes" : "No")"
3118    }
3119
3120    static func ptrMessage(from snapshot: LookupSnapshot) -> SectionMessageViewData? {
3121        if let ptrRecord = snapshot.ptrRecord {
3122            return SectionMessageViewData(text: ptrRecord, isError: false)
3123        }
3124        if let ptrError = snapshot.ptrError {
3125            return SectionMessageViewData(text: ptrError, isError: ptrError != "No A record available" && ptrError != "No PTR record found")
3126        }
3127        return nil
3128    }
3129
3130    static func webCertificateRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3131        guard let sslInfo = snapshot.sslInfo else { return [] }
3132        var rows = [
3133            InfoRowViewData(label: "Common Name", value: sslInfo.commonName, tone: .primary),
3134            InfoRowViewData(label: "Issuer", value: sslInfo.issuer, tone: .primary),
3135            InfoRowViewData(label: "Valid From", value: certificateDateFormatter.string(from: sslInfo.validFrom), tone: .secondary),
3136            InfoRowViewData(label: "Valid Until", value: certificateDateFormatter.string(from: sslInfo.validUntil), tone: .secondary),
3137            InfoRowViewData(label: "Days Until Expiry", value: "\(sslInfo.daysUntilExpiry)", tone: certificateTone(daysRemaining: sslInfo.daysUntilExpiry)),
3138            InfoRowViewData(label: "Chain Depth", value: "\(sslInfo.chainDepth)", tone: .secondary)
3139        ]
3140        if let tlsVersion = sslInfo.tlsVersion {
3141            rows.append(InfoRowViewData(label: "TLS Version", value: tlsVersion, tone: .secondary))
3142        }
3143        if let cipherSuite = sslInfo.cipherSuite {
3144            rows.append(InfoRowViewData(label: "Cipher Suite", value: cipherSuite, tone: .secondary, speechStyle: .technical))
3145        }
3146        if let hstsPreloaded = snapshot.hstsPreloaded {
3147            rows.append(InfoRowViewData(label: "HSTS Preload", value: hstsPreloaded ? "Preloaded" : "Not preloaded", tone: hstsPreloaded ? .success : .secondary))
3148        }
3149        return rows
3150    }
3151
3152    static func webResponseRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3153        var rows: [InfoRowViewData] = []
3154        if let httpStatusCode = snapshot.httpStatusCode {
3155            rows.append(InfoRowViewData(label: "Status", value: "\(httpStatusCode)", tone: .primary))
3156        }
3157        if let httpResponseTimeMs = snapshot.httpResponseTimeMs {
3158            rows.append(InfoRowViewData(label: "Response Time", value: "\(httpResponseTimeMs) ms", tone: .secondary))
3159        }
3160        if let httpProtocol = snapshot.httpProtocol {
3161            rows.append(InfoRowViewData(label: "Protocol", value: httpProtocol, tone: .secondary))
3162        }
3163        if let httpSecurityGrade = snapshot.httpSecurityGrade {
3164            rows.append(InfoRowViewData(label: "Security Grade", value: httpSecurityGrade, tone: securityGradeTone(httpSecurityGrade)))
3165        }
3166        if snapshot.http3Advertised {
3167            rows.append(InfoRowViewData(label: "HTTP/3", value: "Advertised", tone: .secondary))
3168        }
3169        return rows
3170    }
3171
3172    static func redirectRows(from snapshot: LookupSnapshot) -> [RedirectHopViewData] {
3173        snapshot.redirectChain.map {
3174            RedirectHopViewData(
3175                stepLabel: "\($0.stepNumber)",
3176                statusCode: "\($0.statusCode)",
3177                url: $0.url,
3178                isFinal: $0.isFinal
3179            )
3180        }
3181    }
3182
3183    static func emailRows(from snapshot: LookupSnapshot) -> [EmailRowViewData] {
3184        guard let emailSecurity = snapshot.emailSecurity else { return [] }
3185        return [
3186            EmailRowViewData(label: "SPF", status: emailSecurity.spf.found ? "Present" : "Missing", statusTone: emailSecurity.spf.found ? .success : .warning, detail: emailSecurity.spf.value ?? "No record found", auxiliaryDetail: nil),
3187            EmailRowViewData(label: "DMARC", status: emailSecurity.dmarc.found ? "Present" : "Missing", statusTone: emailSecurity.dmarc.found ? .success : .warning, detail: emailSecurity.dmarc.value ?? "No record found", auxiliaryDetail: nil),
3188            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)" }),
3189            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),
3190            EmailRowViewData(label: "BIMI", status: emailSecurity.bimi.found ? "Present" : "Missing", statusTone: emailSecurity.bimi.found ? .success : .warning, detail: emailSecurity.bimi.value ?? "No record found", auxiliaryDetail: nil)
3191        ]
3192    }
3193
3194    static func ownershipRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3195        let ownership = snapshot.ownership
3196
3197        return [
3198            InfoRowViewData(label: "Registrar", value: ownership?.registrar ?? "Unavailable", tone: ownership?.registrar == nil ? .secondary : .primary),
3199            InfoRowViewData(label: "Registered", value: ownership?.createdDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.createdDate == nil ? .secondary : .primary),
3200            InfoRowViewData(label: "Expires", value: ownership?.expirationDate.map(ownershipDateFormatter.string(from:)) ?? "Unavailable", tone: ownership?.expirationDate == nil ? .secondary : .primary),
3201            InfoRowViewData(label: "Status", value: ownership?.status.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.status.isEmpty == false ? .primary : .secondary),
3202            InfoRowViewData(label: "Nameservers", value: ownership?.nameservers.nilIfEmpty?.joined(separator: ", ") ?? "Unavailable", tone: ownership?.nameservers.isEmpty == false ? .primary : .secondary),
3203            InfoRowViewData(label: "Abuse Contact", value: ownership?.abuseEmail ?? "Unavailable", tone: ownership?.abuseEmail == nil ? .secondary : .primary)
3204        ]
3205    }
3206
3207    static func subdomainRows(from snapshot: LookupSnapshot) -> [SubdomainRowViewData] {
3208        snapshot.subdomains.map { subdomain in
3209            SubdomainRowViewData(
3210                hostname: subdomain.hostname,
3211                isInteresting: isInterestingSubdomain(subdomain.hostname)
3212            )
3213        }
3214    }
3215
3216    static func reachabilityRows(from snapshot: LookupSnapshot) -> [ReachabilityRowViewData] {
3217        snapshot.reachabilityResults.map {
3218            ReachabilityRowViewData(
3219                portLabel: "Port \($0.port)",
3220                latencyLabel: $0.latencyMs.map { "\($0) ms" } ?? "—",
3221                statusLabel: $0.reachable ? "Reachable" : "Unreachable",
3222                statusTone: $0.reachable ? .success : .failure
3223            )
3224        }
3225    }
3226
3227    static func locationRows(from snapshot: LookupSnapshot) -> [InfoRowViewData] {
3228        guard let ipGeolocation = snapshot.ipGeolocation else { return [] }
3229        var rows = [InfoRowViewData(label: "IP", value: ipGeolocation.ip, tone: .primary)]
3230        if let org = ipGeolocation.org {
3231            rows.append(InfoRowViewData(label: "Org / ISP", value: org, tone: .secondary))
3232        }
3233        let location = [ipGeolocation.city, ipGeolocation.region, ipGeolocation.countryName].compactMap { $0 }.joined(separator: ", ")
3234        if !location.isEmpty {
3235            rows.append(InfoRowViewData(label: "Location", value: location, tone: .secondary))
3236        }
3237        if let latitude = ipGeolocation.latitude, let longitude = ipGeolocation.longitude {
3238            rows.append(InfoRowViewData(label: "Coordinates", value: "\(latitude), \(longitude)", tone: .secondary))
3239        }
3240        return rows
3241    }
3242
3243    static func portRows(from snapshot: LookupSnapshot, kind: PortScanKind) -> [PortScanRowViewData] {
3244        snapshot.portScanResults
3245            .filter { $0.kind == kind }
3246            .map {
3247                PortScanRowViewData(
3248                    portLabel: "\($0.port)",
3249                    service: $0.service,
3250                    statusLabel: $0.open ? "Open" : "Closed",
3251                    statusTone: $0.open ? .success : .secondary,
3252                    banner: $0.banner,
3253                    durationLabel: $0.durationMs.map { "\($0) ms" }
3254                )
3255            }
3256    }
3257
3258    static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
3259        snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
3260    }
3261
3262    static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
3263        snapshot.redirectChain.last?.url
3264    }
3265
3266    static func httpsSummary(from snapshot: LookupSnapshot) -> String {
3267        if snapshot.sslInfo != nil {
3268            return "Valid"
3269        }
3270        if let sslError = snapshot.sslError {
3271            return sslError.localizedCaseInsensitiveContains("certificate") ? "Invalid" : "Failed"
3272        }
3273        return "Unavailable"
3274    }
3275
3276    private static func httpsSummaryTone(from snapshot: LookupSnapshot) -> ResultTone {
3277        if snapshot.sslInfo != nil {
3278            return .success
3279        }
3280        return snapshot.sslError == nil ? .secondary : .failure
3281    }
3282
3283    static func emailSummary(from snapshot: LookupSnapshot) -> String {
3284        guard let emailSecurity = snapshot.emailSecurity else {
3285            return snapshot.emailSecurityError ?? "Unavailable"
3286        }
3287        return "SPF \(emailSecurity.spf.found ? "Yes" : "No") / DMARC \(emailSecurity.dmarc.found ? "Yes" : "No")"
3288    }
3289
3290    private static func certificateStatusLabel(from snapshot: LookupSnapshot) -> String {
3291        guard let sslInfo = snapshot.sslInfo else {
3292            return snapshot.sslError ?? "Unavailable"
3293        }
3294
3295        switch DomainDiffService.certificateWarningLevel(for: snapshot) {
3296        case .critical:
3297            return "Critical (\(sslInfo.daysUntilExpiry)d)"
3298        case .warning:
3299            return "Warning (\(sslInfo.daysUntilExpiry)d)"
3300        case .none:
3301            return "Healthy (\(sslInfo.daysUntilExpiry)d)"
3302        }
3303    }
3304
3305    private static func certificateBadgeLabel(from snapshot: LookupSnapshot) -> String? {
3306        guard snapshot.sslInfo != nil else { return nil }
3307        return certificateStatusLabel(from: snapshot)
3308    }
3309
3310    private static func certificateStatusTone(from snapshot: LookupSnapshot) -> ResultTone {
3311        guard let daysRemaining = snapshot.sslInfo?.daysUntilExpiry else {
3312            return snapshot.sslError == nil ? .secondary : .failure
3313        }
3314        return certificateTone(daysRemaining: daysRemaining)
3315    }
3316
3317    private static func certificateTone(daysRemaining: Int) -> ResultTone {
3318        if daysRemaining < 14 {
3319            return .failure
3320        }
3321        if daysRemaining < 30 {
3322            return .warning
3323        }
3324        return .success
3325    }
3326
3327    static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
3328        switch status {
3329        case .available:
3330            return "Available"
3331        case .registered:
3332            return "Registered"
3333        case .unknown, .none:
3334            return "Unknown"
3335        }
3336    }
3337
3338    private static func availabilityInference(from snapshot: LookupSnapshot) -> String {
3339        switch snapshot.availabilityResult?.status {
3340        case .registered:
3341            return "Likely registered"
3342        case .available:
3343            return "Possibly available"
3344        case .unknown, .none:
3345            return "Unclear"
3346        }
3347    }
3348
3349    private static func availabilityTone(_ status: DomainAvailabilityStatus?) -> ResultTone {
3350        switch status {
3351        case .available:
3352            return .success
3353        case .registered:
3354            return .warning
3355        case .unknown, .none:
3356            return .secondary
3357        }
3358    }
3359
3360    private static func sourceTone(for snapshot: LookupSnapshot) -> ResultTone {
3361        if snapshot.statusMessage != nil {
3362            return .warning
3363        }
3364
3365        switch snapshot.resultSource {
3366        case .live:
3367            return .success
3368        case .cached:
3369            return .secondary
3370        case .mixed:
3371            return .warning
3372        case .snapshot:
3373            return .warning
3374        }
3375    }
3376
3377    private static func securityGradeTone(_ grade: String) -> ResultTone {
3378        switch grade {
3379        case "A", "B":
3380            return .success
3381        case "C":
3382            return .warning
3383        case "D", "F":
3384            return .failure
3385        default:
3386            return .secondary
3387        }
3388    }
3389
3390    static func durationLabel(_ durationMs: Int?) -> String {
3391        durationMs.map { "\($0) ms" } ?? "Unavailable"
3392    }
3393
3394    private static let certificateDateFormatter: DateFormatter = {
3395        let formatter = DateFormatter()
3396        formatter.dateStyle = .medium
3397        formatter.timeStyle = .short
3398        return formatter
3399    }()
3400
3401    private static let ownershipDateFormatter: DateFormatter = {
3402        let formatter = DateFormatter()
3403        formatter.dateStyle = .medium
3404        formatter.timeStyle = .none
3405        return formatter
3406    }()
3407
3408    private func conciseExternalMessage(_ message: String, fallback: String) -> String {
3409        let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
3410        if trimmed.isEmpty {
3411            return fallback
3412        }
3413        if trimmed.localizedCaseInsensitiveContains("rate") {
3414            return "Rate limited. Try again later."
3415        }
3416        if trimmed.localizedCaseInsensitiveContains("invalid") {
3417            return "External data was invalid."
3418        }
3419        if trimmed.localizedCaseInsensitiveContains("network") {
3420            return "External data is offline."
3421        }
3422        return trimmed
3423    }
3424
3425    private static func isInterestingSubdomain(_ hostname: String) -> Bool {
3426        let keywords = ["admin", "api", "dev", "staging", "test", "internal"]
3427        let labels = hostname.lowercased().split(separator: ".").map(String.init)
3428        return labels.contains { label in
3429            keywords.contains(where: { label.contains($0) })
3430        }
3431    }
3432}
3433