DomainReportExporter.swift

v5.1.0
domain-dig/DomainReportExporter.swift history · blame · raw

814 lines · 33851 bytes

  1import Foundation
  2
  3#if canImport(UIKit)
  4import UIKit
  5#endif
  6
  7enum DomainExportFormat: String, CaseIterable, Identifiable, Codable {
  8    case text = "txt"
  9    case csv = "csv"
 10    case json = "json"
 11    case markdown = "md"
 12    case pdf = "pdf"
 13
 14    var fileExtension: String { rawValue }
 15    var id: String { fileExtension }
 16
 17    var title: String {
 18        switch self {
 19        case .text: return "TXT"
 20        case .csv: return "CSV"
 21        case .json: return "JSON"
 22        case .markdown: return "Markdown"
 23        case .pdf: return "PDF"
 24        }
 25    }
 26}
 27
 28enum DomainReportExporter {
 29    static func data(for report: DomainReport, format: DomainExportFormat) throws -> Data {
 30        switch format {
 31        case .text:
 32            return Data(text(for: report).utf8)
 33        case .csv:
 34            return Data(csv(for: [report]).utf8)
 35        case .json:
 36            return try jsonEncoder.encode(report)
 37        case .markdown:
 38            return Data(markdown(for: report).utf8)
 39        case .pdf:
 40            return pdfData(fromMarkdown: markdown(for: report))
 41        }
 42    }
 43
 44    static func data(for reports: [DomainReport], format: DomainExportFormat, title: String) throws -> Data {
 45        switch format {
 46        case .text:
 47            return Data(batchText(for: reports, title: title).utf8)
 48        case .csv:
 49            return Data(csv(for: reports).utf8)
 50        case .json:
 51            return try jsonEncoder.encode(reports)
 52        case .markdown:
 53            return Data(batchMarkdown(for: reports, title: title).utf8)
 54        case .pdf:
 55            return pdfData(fromMarkdown: batchMarkdown(for: reports, title: title))
 56        }
 57    }
 58
 59    /// Renders `text(for:)`'s content as Markdown: the leading title becomes an
 60    /// H1, `appendSection`'s "Title\n----" underlines become H2 headers, and
 61    /// other non-empty lines that aren't already list items become bullets.
 62    /// This reuses the exact same section content as the text export rather
 63    /// than re-deriving it, so the two formats never drift.
 64    static func markdown(for report: DomainReport) -> String {
 65        markdown(fromPlainText: text(for: report), title: "DomainDig Report")
 66    }
 67
 68    static func batchMarkdown(for reports: [DomainReport], title: String) -> String {
 69        markdown(fromPlainText: batchText(for: reports, title: title), title: title)
 70    }
 71
 72    private static func markdown(fromPlainText text: String, title: String) -> String {
 73        let lines = text.components(separatedBy: "\n")
 74        var output: [String] = ["# \(title)", ""]
 75        var index = 0
 76        while index < lines.count {
 77            let line = lines[index]
 78            if index == 0, line == title {
 79                index += 1
 80                if index < lines.count, isUnderline(lines[index], for: line) {
 81                    index += 1
 82                }
 83                continue
 84            }
 85            if index + 1 < lines.count, !line.isEmpty, isUnderline(lines[index + 1], for: line) {
 86                output.append("")
 87                output.append("## \(line)")
 88                index += 2
 89                continue
 90            }
 91            if isRule(line) {
 92                output.append("")
 93                output.append("---")
 94                index += 1
 95                continue
 96            }
 97            if line.isEmpty || line.hasPrefix("-") || line.hasPrefix("  ") {
 98                output.append(line)
 99            } else {
100                output.append("- \(line)")
101            }
102            index += 1
103        }
104        return output.joined(separator: "\n")
105    }
106
107    /// True when `line` is a run of `-` or `=` exactly as long as the heading it
108    /// underlines. `batchText` uses `=` for the document title, `appendSection`
109    /// uses `-` for section headers.
110    private static func isUnderline(_ line: String, for heading: String) -> Bool {
111        guard !heading.isEmpty else { return false }
112        return line == String(repeating: "-", count: heading.count)
113            || line == String(repeating: "=", count: heading.count)
114    }
115
116    /// True for a standalone divider not attached to a heading — `batchText`
117    /// emits a fixed 48-character `=` run between reports.
118    private static func isRule(_ line: String) -> Bool {
119        line.count >= 3 && (line.allSatisfy { $0 == "=" } || line.allSatisfy { $0 == "-" })
120    }
121
122    /// Renders Markdown as a simple monospaced multi-page PDF. Foundation-only
123    /// consumers (no UIKit available) get the Markdown bytes back instead.
124    static func pdfData(fromMarkdown markdown: String) -> Data {
125        #if canImport(UIKit)
126        let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792))
127        return renderer.pdfData { context in
128            let lines = markdown.components(separatedBy: .newlines)
129            let paragraphStyle = NSMutableParagraphStyle()
130            paragraphStyle.lineBreakMode = .byWordWrapping
131            let attributes: [NSAttributedString.Key: Any] = [
132                .font: UIFont.monospacedSystemFont(ofSize: 11, weight: .regular),
133                .paragraphStyle: paragraphStyle
134            ]
135
136            var yOffset: CGFloat = 36
137            context.beginPage()
138
139            for line in lines {
140                if yOffset > 744 {
141                    context.beginPage()
142                    yOffset = 36
143                }
144
145                let renderedLine = NSString(string: line.isEmpty ? " " : line)
146                renderedLine.draw(
147                    in: CGRect(x: 36, y: yOffset, width: 540, height: 22),
148                    withAttributes: attributes
149                )
150                yOffset += 16
151            }
152        }
153        #else
154        return Data(markdown.utf8)
155        #endif
156    }
157
158    static func text(for report: DomainReport) -> String {
159        var lines = headerLines(report)
160        appendSection("Summary", to: &lines) { summarySection(report) }
161        appendSection("Risk", to: &lines) { riskSection(report) }
162        appendSection("Insights", to: &lines) { insightsSection(report) }
163        appendSection("Ownership", to: &lines) { ownershipSection(report) }
164        appendSection("Ownership History", to: &lines) { ownershipHistorySection(report) }
165        appendSection("DNS", to: &lines) { dnsSection(report) }
166        appendSection("DNS History", to: &lines) { dnsHistorySection(report) }
167        appendSection("Web", to: &lines) { webSection(report) }
168        appendSection("Email", to: &lines) { emailSection(report) }
169        appendSection("Network", to: &lines) { networkSection(report) }
170        appendSection("Subdomains", to: &lines) { subdomainsSection(report) }
171        appendSection("Pricing", to: &lines) { pricingSection(report) }
172        appendSection("Changes", to: &lines) { changesSection(report) }
173        return lines.joined(separator: "\n")
174    }
175
176    /// The report's title block: what was looked up, when, how, and with what caveats.
177    private static func headerLines(_ report: DomainReport) -> [String] {
178        var lines = [
179            "DomainDig Report",
180            "Domain: \(report.domain)",
181            "Timestamp: \(textDateFormatter.string(from: report.timestamp))",
182            "App Version: \(report.metadata.appVersion)",
183            "Resolver: \(report.metadata.resolverDisplayName)",
184            "Resolver URL: \(report.metadata.resolverURLString)",
185            "Source: \(report.provenance.source.label)",
186            "Availability: \(availabilityLabel(report.availability))",
187            "Availability Confidence: \(report.availabilityConfidence?.title ?? "N/A")"
188        ]
189
190        if report.metadata.isPartialSnapshot {
191            lines.append("Snapshot Integrity: Partial snapshot")
192        }
193        if let auditNote = report.metadata.auditNote, !auditNote.isEmpty {
194            lines.append("Audit Note: \(auditNote)")
195        }
196        if !report.provenance.dataSources.isEmpty {
197            lines.append("Data Sources: \(report.provenance.dataSources.joined(separator: ", "))")
198        }
199        if !report.metadata.validationIssues.isEmpty {
200            lines.append("Validation: \(report.metadata.validationIssues.joined(separator: " | "))")
201        }
202        if let workflowContext = report.workflowContext {
203            lines.append("Workflow Context: \(workflowContext.workflowName ?? workflowContext.source)")
204        }
205        return lines
206    }
207
208    private static func summarySection(_ report: DomainReport) -> [String] {
209        [
210            "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
211            "Risk Score: \(report.riskAssessment.score) (\(report.riskAssessment.level.title))",
212            "TLS Status: \(report.web.tlsStatus)",
213            "HTTP: \(httpSummary(for: report))",
214            "Email: \(report.email.summary)",
215            "Subdomains: \(report.subdomains.count)",
216            "Extended Subdomains: \(report.extendedSubdomains.count)",
217            "External Price: \(report.domainPricing?.estimatedPrice ?? "Unavailable")",
218            "Reputation: \(report.reputation?.status.title ?? "Unavailable")"
219        ]
220    }
221
222    private static func riskSection(_ report: DomainReport) -> [String] {
223        var values = [
224            "Score: \(report.riskAssessment.score)",
225            "Level: \(report.riskAssessment.level.title)"
226        ]
227        if report.riskAssessment.factors.isEmpty {
228            values.append("Factors: None")
229        } else {
230            values.append("Factors:")
231            for factor in report.riskAssessment.factors {
232                values.append("  [\(factor.impact.rawValue)] \(factor.description)")
233            }
234        }
235        return values
236    }
237
238    private static func insightsSection(_ report: DomainReport) -> [String] {
239        report.insights.isEmpty ? ["No deterministic insights triggered"] : report.insights.map { "- \($0)" }
240    }
241
242    private static func ownershipSection(_ report: DomainReport) -> [String] {
243        var ownershipLines = [
244            "Registrar: \(report.ownership?.registrar ?? "Unavailable")",
245            "Confidence: \(report.ownershipConfidence?.title ?? "N/A")",
246            "Created: \(ownershipDateLabel(report.ownership?.createdDate))",
247            "Expires: \(ownershipDateLabel(report.ownership?.expirationDate))",
248            "Registrant: \(report.ownership?.registrant ?? "Unavailable")",
249            "Nameservers: \(joined(report.ownership?.nameservers) ?? "Unavailable")",
250            "Status: \(joined(report.ownership?.status) ?? "Unavailable")",
251            "Abuse Contact: \(report.ownership?.abuseEmail ?? "Unavailable")"
252        ]
253        if let provenance = report.sectionProvenance[.ownership] {
254            ownershipLines.append("Provenance: \(provenanceLabel(provenance))")
255        }
256        if let error = report.dns.error, report.ownership == nil {
257            ownershipLines.append("Error: \(error)")
258        }
259        return ownershipLines
260    }
261
262    private static func ownershipHistorySection(_ report: DomainReport) -> [String] {
263        guard !report.ownershipHistory.isEmpty else {
264            return ["No ownership history available"]
265        }
266
267        return report.ownershipHistory.map { event in
268            [
269                textDateFormatter.string(from: event.date),
270                event.summary,
271                "source=\(event.source)"
272            ].joined(separator: " | ")
273        }
274    }
275
276    private static func dnsSection(_ report: DomainReport) -> [String] {
277        var dnsLines = [
278            "Lookup Duration: \(durationLabel(report.dns.lookupDurationMs))",
279            "Primary IP: \(report.dns.primaryIP ?? "Unavailable")",
280            "PTR: \(report.dns.ptrRecord ?? report.dns.ptrError ?? "Unavailable")",
281            "DNSSEC: \(dnssecLabel(report.dns.dnssecSigned))",
282            "Patterns: \(report.dns.patternSummary.patterns.joined(separator: " | ").nilIfEmpty ?? "None")"
283        ]
284        if let provenance = report.sectionProvenance[.dns] {
285            dnsLines.append("Provenance: \(provenanceLabel(provenance))")
286        }
287        if let error = report.dns.error {
288            dnsLines.append("Error: \(error)")
289        }
290        if report.dns.recordSections.isEmpty {
291            dnsLines.append("Records: None")
292        } else {
293            dnsLines.append("Records:")
294            for section in report.dns.recordSections {
295                var seen: Set<String> = []
296                let values = (section.records + section.wildcardRecords)
297                    .map(\.value)
298                    .filter { seen.insert($0).inserted }
299                let renderedValues = values.isEmpty ? "None" : values.joined(separator: " | ")
300                dnsLines.append("  \(section.recordType.rawValue): \(renderedValues)")
301            }
302        }
303        return dnsLines
304    }
305
306    private static func dnsHistorySection(_ report: DomainReport) -> [String] {
307        guard !report.dnsHistory.isEmpty else {
308            return ["No DNS history available"]
309        }
310
311        return report.dnsHistory.map { event in
312            [
313                textDateFormatter.string(from: event.date),
314                event.summary,
315                "A=\(event.aRecords.joined(separator: " | ").nilIfEmpty ?? "-")",
316                "NS=\(event.nameservers.joined(separator: " | ").nilIfEmpty ?? "-")",
317                "source=\(event.source)"
318            ].joined(separator: " | ")
319        }
320    }
321
322    private static func webSection(_ report: DomainReport) -> [String] {
323        var webLines = [
324            "TLS Status: \(report.web.tlsStatus)",
325            "TLS Grade: \(report.web.tlsGrade.rawValue)",
326            "TLS Highlights: \(report.web.tlsHighlights.joined(separator: " | "))",
327            "Certificate Warning: \(report.web.certificateWarningLevel.title)",
328            "Security Grade: \(report.web.securityGrade ?? "Unavailable")",
329            "HTTP Status: \(report.web.statusCode.map(String.init) ?? "Unavailable")",
330            "Protocol: \(report.web.httpProtocol ?? "Unavailable")",
331            "HTTP/3 Advertised: \(report.web.http3Advertised ? "Yes" : "No")",
332            "Final URL: \(report.web.finalURL ?? "Unavailable")",
333            "HSTS Preloaded: \(booleanLabel(report.web.hstsPreloaded))",
334            "Header Count: \(report.web.headerCount)"
335        ]
336        if let provenance = report.sectionProvenance[.ssl] {
337            webLines.append("TLS Provenance: \(provenanceLabel(provenance))")
338        }
339        if let provenance = report.sectionProvenance[.httpHeaders] {
340            webLines.append("HTTP Provenance: \(provenanceLabel(provenance))")
341        }
342        if let provenance = report.sectionProvenance[.redirectChain] {
343            webLines.append("Redirect Provenance: \(provenanceLabel(provenance))")
344        }
345        if let tlsError = report.web.tlsError {
346            webLines.append("TLS Error: \(tlsError)")
347        }
348        if let headersError = report.web.headersError {
349            webLines.append("Headers Error: \(headersError)")
350        }
351        if let redirectError = report.web.redirectError {
352            webLines.append("Redirect Error: \(redirectError)")
353        }
354        if !report.web.headers.isEmpty {
355            webLines.append("Headers:")
356            for header in report.web.headers {
357                webLines.append("  \(header.name): \(header.value)")
358            }
359        }
360        if !report.web.redirectChain.isEmpty {
361            webLines.append("Redirect Chain:")
362            for hop in report.web.redirectChain {
363                webLines.append("  \(hop.stepNumber). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
364            }
365        }
366        return webLines
367    }
368
369    private static func emailSection(_ report: DomainReport) -> [String] {
370        var emailLines = [report.email.summary]
371        if let grade = report.email.grade {
372            emailLines.append("Grade: \(grade.rawValue)")
373        }
374        if !report.email.reasons.isEmpty {
375            emailLines.append("Why: \(report.email.reasons.joined(separator: " | "))")
376        }
377        emailLines.append("Confidence: \(report.emailConfidence?.title ?? "N/A")")
378        if let provenance = report.sectionProvenance[.emailSecurity] {
379            emailLines.append("Provenance: \(provenanceLabel(provenance))")
380        }
381        if let records = report.email.records {
382            emailLines.append("SPF: \(recordLabel(records.spf))")
383            emailLines.append("DMARC: \(recordLabel(records.dmarc))")
384            emailLines.append("DKIM: \(recordLabel(records.dkim))")
385            emailLines.append("BIMI: \(recordLabel(records.bimi))")
386            emailLines.append("MTA-STS: \(records.mtaSts?.txtFound == true ? records.mtaSts?.policyMode ?? "found" : "Unavailable")")
387        }
388        if let error = report.email.error {
389            emailLines.append("Error: \(error)")
390        }
391        return emailLines
392    }
393
394    private static func networkSection(_ report: DomainReport) -> [String] {
395        var networkLines = [
396            "Reachability: \(report.network.reachabilitySummary)",
397            "Geolocation: \(report.network.geolocationSummary)",
398            "Geolocation Confidence: \(report.geolocationConfidence?.title ?? "N/A")",
399            "Open Ports: \(report.network.openPorts.map(String.init).joined(separator: ", ").nilIfEmpty ?? "None")"
400        ]
401        if let provenance = report.sectionProvenance[.ipGeolocation] {
402            networkLines.append("Geolocation Provenance: \(provenanceLabel(provenance))")
403        }
404        if let error = report.network.reachabilityError {
405            networkLines.append("Reachability Error: \(error)")
406        }
407        if let error = report.network.geolocationError {
408            networkLines.append("Geolocation Error: \(error)")
409        }
410        if let error = report.network.portScanError {
411            networkLines.append("Port Scan Error: \(error)")
412        }
413        if !report.network.portScan.isEmpty {
414            networkLines.append("Port Scan:")
415            for result in report.network.portScan {
416                networkLines.append(
417                    "  \(result.port) \(result.service): \(result.open ? "open" : "closed")\(result.banner.map { " banner=\($0)" } ?? "")"
418                )
419            }
420        }
421        return networkLines
422    }
423
424    private static func subdomainsSection(_ report: DomainReport) -> [String] {
425        var values = ["Confidence: \(report.subdomainConfidence?.title ?? "N/A")"]
426        if let provenance = report.sectionProvenance[.subdomains] {
427            values.append("Provenance: \(provenanceLabel(provenance))")
428        }
429        if report.subdomains.isEmpty {
430            values.append("None")
431            return values
432        }
433        if !report.subdomainGroups.isEmpty {
434            values.append("Groups: \(report.subdomainGroups.map { "\($0.label): \($0.subdomains.count)" }.joined(separator: " | "))")
435        }
436        values.append(contentsOf: report.subdomains.map { "- \($0)" })
437        if !report.extendedSubdomains.isEmpty {
438            values.append("Extended:")
439            values.append(contentsOf: report.extendedSubdomains.map { "- \($0)" })
440        }
441        return values
442    }
443
444    private static func pricingSection(_ report: DomainReport) -> [String] {
445        guard let pricing = report.domainPricing else {
446            return ["External pricing unavailable"]
447        }
448
449        return [
450            "Estimated Price: \(pricing.estimatedPrice ?? "Unavailable")",
451            "Premium: \(pricing.premiumIndicator == true ? "Yes" : "No")",
452            "Resale: \(pricing.resaleSignal ?? "Unavailable")",
453            "Auction: \(pricing.auctionSignal ?? "Unavailable")",
454            "Source: \(pricing.source)",
455            "Collected: \(textDateFormatter.string(from: pricing.collectedAt))"
456        ]
457    }
458
459    private static func changesSection(_ report: DomainReport) -> [String] {
460        guard let changeSummary = report.changeSummary else {
461            return ["No comparison available"]
462        }
463
464        var values = [
465            "Has Changes: \(changeSummary.hasChanges ? "Yes" : "No")",
466            "Severity: \(changeSummary.severity.title)",
467            "Impact: \(changeSummary.impactClassification.title)",
468            "Inferred Summary: \(changeSummary.message)",
469            "Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))"
470        ]
471        if let riskScoreDelta = changeSummary.riskScoreDelta {
472            values.append("Risk Delta: \(riskScoreDelta >= 0 ? "+" : "")\(riskScoreDelta)")
473        }
474        if !changeSummary.insights.isEmpty {
475            values.append("Insights: \(changeSummary.insights.joined(separator: " | "))")
476        }
477        if !changeSummary.observedFacts.isEmpty {
478            values.append("Observed: \(changeSummary.observedFacts.joined(separator: " | "))")
479        }
480        if let contextNote = changeSummary.contextNote {
481            values.append("Context: \(contextNote)")
482        }
483        return values
484    }
485
486    static func batchText(for reports: [DomainReport], title: String) -> String {
487        guard !reports.isEmpty else {
488            return "\(title)\nNo results available."
489        }
490
491        var lines = [title, String(repeating: "=", count: title.count), ""]
492        for (index, report) in reports.enumerated() {
493            if index > 0 {
494                lines.append("")
495                lines.append(String(repeating: "=", count: 48))
496                lines.append("")
497            }
498            lines.append(text(for: report))
499        }
500        return lines.joined(separator: "\n")
501    }
502
503    static func csv(for reports: [DomainReport]) -> String {
504        csv(for: reports, workflowInsights: [])
505    }
506
507    static func csv(for reports: [DomainReport], workflowInsights: [WorkflowInsight]) -> String {
508        let workflowInsightSummary = workflowInsights.map(\.description).joined(separator: " | ")
509        let headers = [
510            "domain",
511            "timestamp",
512            "app_version",
513            "result_source",
514            "resolver",
515            "availability",
516            "risk_score",
517            "risk_level",
518            "risk_factors",
519            "insights",
520            "availability_confidence",
521            "registrar",
522            "ownership_confidence",
523            "ownership_expires",
524            "nameservers",
525            "primary_ip",
526            "ptr_record",
527            "dnssec_signed",
528            "dns_patterns",
529            "tls_status",
530            "tls_grade",
531            "tls_highlights",
532            "certificate_warning_level",
533            "hsts_preloaded",
534            "http_status",
535            "http_security_grade",
536            "final_url",
537            "email_summary",
538            "email_grade",
539            "email_confidence",
540            "subdomain_count",
541            "extended_subdomain_count",
542            "subdomain_groups",
543            "subdomain_confidence",
544            "subdomains",
545            "extended_subdomains",
546            "ownership_history",
547            "dns_history",
548            "pricing_estimated",
549            "pricing_premium",
550            "pricing_resale_signal",
551            "pricing_auction_signal",
552            "pricing_source",
553            "reputation_status",
554            "reputation_listed_sources",
555            "open_ports",
556            "reachability_summary",
557            "geolocation_summary",
558            "geolocation_confidence",
559            "data_sources",
560            "audit_note",
561            "partial_snapshot",
562            "workflow_name",
563            "workflow_source",
564            "cached_sections",
565            "change_summary",
566            "change_impact",
567            "workflow_insights"
568        ]
569
570        let rows = reports.map { report in
571            let expirationDate = report.ownership?.expirationDate.map(csvDateFormatter.string(from:)) ?? ""
572            let nameservers = joined(report.ownership?.nameservers) ?? ""
573            let dnssecSigned = report.dns.dnssecSigned.map { $0 ? "true" : "false" } ?? ""
574            let hstsPreloaded = report.web.hstsPreloaded.map { $0 ? "true" : "false" } ?? ""
575            let httpStatus = report.web.statusCode.map(String.init) ?? ""
576            let subdomainCount = String(report.subdomains.count)
577            let subdomains = report.subdomains.joined(separator: " | ")
578            let extendedSubdomains = report.extendedSubdomains.joined(separator: " | ")
579            let openPorts = report.network.openPorts.map(String.init).joined(separator: " | ")
580            let riskFactors = report.riskAssessment.factors.map(\.description).joined(separator: " | ")
581            let insights = report.insights.joined(separator: " | ")
582            let dnsPatterns = report.dns.patternSummary.patterns.joined(separator: " | ")
583            let tlsHighlights = report.web.tlsHighlights.joined(separator: " | ")
584            let subdomainGroups = report.subdomainGroups.map { "\($0.label):\($0.subdomains.count)" }.joined(separator: " | ")
585            let ownershipHistory = report.ownershipHistory.map { "\($0.date.ISO8601Format()) \($0.summary)" }.joined(separator: " | ")
586            let dnsHistory = report.dnsHistory.map { "\($0.date.ISO8601Format()) \($0.summary)" }.joined(separator: " | ")
587            let reputationStatus = report.reputation?.status.rawValue ?? ""
588            let reputationListedSources = report.reputation?.listedSources.joined(separator: " | ") ?? ""
589
590            return [
591                report.domain,
592                csvDateFormatter.string(from: report.timestamp),
593                report.appVersion,
594                report.resultSource.rawValue,
595                report.resolverDisplayName,
596                availabilityLabel(report.availability),
597                "\(report.riskAssessment.score)",
598                report.riskAssessment.level.rawValue,
599                riskFactors,
600                insights,
601                report.availabilityConfidence?.rawValue ?? "",
602                report.ownership?.registrar ?? "",
603                report.ownershipConfidence?.rawValue ?? "",
604                expirationDate,
605                nameservers,
606                report.dns.primaryIP ?? "",
607                report.dns.ptrRecord ?? "",
608                dnssecSigned,
609                dnsPatterns,
610                report.web.tlsStatus,
611                report.web.tlsGrade.rawValue,
612                tlsHighlights,
613                report.web.certificateWarningLevel.rawValue,
614                hstsPreloaded,
615                httpStatus,
616                report.web.securityGrade ?? "",
617                report.web.finalURL ?? "",
618                report.email.summary,
619                report.email.grade?.rawValue ?? "",
620                report.emailConfidence?.rawValue ?? "",
621                subdomainCount,
622                String(report.extendedSubdomains.count),
623                subdomainGroups,
624                report.subdomainConfidence?.rawValue ?? "",
625                subdomains,
626                extendedSubdomains,
627                ownershipHistory,
628                dnsHistory,
629                report.domainPricing?.estimatedPrice ?? "",
630                report.domainPricing?.premiumIndicator == true ? "true" : "false",
631                report.domainPricing?.resaleSignal ?? "",
632                report.domainPricing?.auctionSignal ?? "",
633                report.domainPricing?.source ?? "",
634                reputationStatus,
635                reputationListedSources,
636                openPorts,
637                report.network.reachabilitySummary,
638                report.network.geolocationSummary,
639                report.geolocationConfidence?.rawValue ?? "",
640                report.provenance.dataSources.joined(separator: " | "),
641                report.metadata.auditNote ?? "",
642                report.metadata.isPartialSnapshot ? "true" : "false",
643                report.workflowContext?.workflowName ?? "",
644                report.workflowContext?.source ?? "",
645                report.metadata.cachedSections.map(\.rawValue).joined(separator: " | "),
646                report.changeSummary?.message ?? "",
647                report.changeSummary?.impactClassification.rawValue ?? "",
648                workflowInsightSummary
649            ]
650        }
651
652        return ([headers] + rows)
653            .map { row in row.map(csvEscaped).joined(separator: ",") }
654            .joined(separator: "\n")
655    }
656
657    static func timelineText(for reports: [DomainReport], domain: String, includeDiffSummary: Bool) -> String {
658        guard !reports.isEmpty else {
659            return "Timeline Export\nNo snapshots available for \(domain)."
660        }
661
662        var lines = [
663            "DomainDig Timeline Export",
664            "Domain: \(domain)",
665            "Snapshots: \(reports.count)"
666        ]
667
668        for report in reports.sorted(by: { $0.timestamp > $1.timestamp }) {
669            lines.append("")
670            lines.append("\(textDateFormatter.string(from: report.timestamp))")
671            lines.append("Summary: \(report.changeSummary?.message ?? "No change summary")")
672            lines.append("Severity: \(report.changeSummary?.severity.title ?? "N/A")")
673            if includeDiffSummary, let changeSummary = report.changeSummary {
674                lines.append("Changed Sections: \(changeSummary.changedSections.joined(separator: ", ").nilIfEmpty ?? "None")")
675            }
676        }
677
678        return lines.joined(separator: "\n")
679    }
680
681    static func timelineData(for reports: [DomainReport], domain: String, includeDiffSummary: Bool) throws -> Data {
682        struct TimelineExportEntry: Codable {
683            let timestamp: Date
684            let summary: String?
685            let severity: String?
686            let changedSections: [String]?
687        }
688
689        struct TimelineExportPayload: Codable {
690            let domain: String
691            let exportedAt: Date
692            let snapshots: [TimelineExportEntry]
693        }
694
695        let payload = TimelineExportPayload(
696            domain: domain,
697            exportedAt: Date(),
698            snapshots: reports
699                .sorted(by: { $0.timestamp > $1.timestamp })
700                .map { report in
701                    TimelineExportEntry(
702                        timestamp: report.timestamp,
703                        summary: report.changeSummary?.message,
704                        severity: report.changeSummary?.severity.title,
705                        changedSections: includeDiffSummary ? report.changeSummary?.changedSections : nil
706                    )
707                }
708        )
709
710        return try jsonEncoder.encode(payload)
711    }
712
713    private static func appendSection(_ title: String, to lines: inout [String], body: () -> [String]) {
714        lines.append("")
715        lines.append(title)
716        lines.append(String(repeating: "-", count: title.count))
717        lines.append(contentsOf: body())
718    }
719
720    private static func availabilityLabel(_ status: DomainAvailabilityStatus) -> String {
721        switch status {
722        case .available:
723            return "Available"
724        case .registered:
725            return "Registered"
726        case .unknown:
727            return "Unknown"
728        }
729    }
730
731    private static func joined(_ values: [String]?) -> String? {
732        guard let values, !values.isEmpty else { return nil }
733        return values.joined(separator: " | ")
734    }
735
736    private static func dnssecLabel(_ value: Bool?) -> String {
737        switch value {
738        case true:
739            return "Signed"
740        case false:
741            return "Unsigned"
742        case nil:
743            return "Unavailable"
744        }
745    }
746
747    private static func ownershipDateLabel(_ date: Date?) -> String {
748        guard let date else { return "Unavailable" }
749        return textDateFormatter.string(from: date)
750    }
751
752    private static func durationLabel(_ durationMs: Int?) -> String {
753        durationMs.map { "\($0) ms" } ?? "Unavailable"
754    }
755
756    private static func httpSummary(for report: DomainReport) -> String {
757        let parts = [report.web.statusCode.map(String.init), report.web.securityGrade].compactMap { $0 }
758        return parts.isEmpty ? report.web.headersError ?? "Unavailable" : parts.joined(separator: " / ")
759    }
760
761    private static func booleanLabel(_ value: Bool?) -> String {
762        guard let value else { return "Unavailable" }
763        return value ? "Yes" : "No"
764    }
765
766    private static func recordLabel(_ record: EmailSecurityRecord) -> String {
767        if record.found {
768            return record.value ?? "Present"
769        }
770        return "Unavailable"
771    }
772
773    private static func provenanceLabel(_ provenance: SectionProvenance) -> String {
774        [
775            provenance.source,
776            provenance.provider,
777            provenance.resolver.map { "resolver=\($0)" },
778            provenance.resultSource.label.lowercased(),
779            textDateFormatter.string(from: provenance.collectedAt)
780        ]
781        .compactMap { $0 }
782        .joined(separator: " | ")
783    }
784
785    private static let textDateFormatter: DateFormatter = {
786        let formatter = DateFormatter()
787        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
788        return formatter
789    }()
790
791    private static let csvDateFormatter: ISO8601DateFormatter = {
792        let formatter = ISO8601DateFormatter()
793        formatter.formatOptions = [.withInternetDateTime]
794        return formatter
795    }()
796
797    private static let jsonEncoder: JSONEncoder = {
798        let encoder = JSONEncoder()
799        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
800        encoder.dateEncodingStrategy = .iso8601
801        return encoder
802    }()
803
804    nonisolated private static func csvEscaped(_ value: String) -> String {
805        let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
806        return "\"\(escaped)\""
807    }
808}
809
810private extension String {
811    var nilIfEmpty: String? {
812        isEmpty ? nil : self
813    }
814}