DomainDig/DomainReportExporter.swift

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

821 lines · 34221 bytes

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