summaryrefslogtreecommitdiff
path: root/DomainDig/Models.swift
blob: f872aabdc8ef28e6013a3f8ba96adcf3c8dd606b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
import Foundation

enum ServiceResult<Value> {
    case success(Value)
    case empty(String)
    case error(String)
}

enum ConfidenceLevel: String, Codable {
    case high
    case medium
    case low

    var title: String {
        rawValue.capitalized
    }
}

enum InspectionErrorKind: String, Codable {
    case network
    case timeout
    case rateLimited
    case parsing
    case unsupported
    case unavailable
    case unknown

    var title: String {
        switch self {
        case .network:
            return "Network"
        case .timeout:
            return "Timeout"
        case .rateLimited:
            return "Rate limited"
        case .parsing:
            return "Parsing"
        case .unsupported:
            return "Unsupported"
        case .unavailable:
            return "Unavailable"
        case .unknown:
            return "Unknown"
        }
    }
}

struct InspectionFailure: Codable, Equatable {
    let kind: InspectionErrorKind
    let message: String
    let details: String?
}

struct SectionProvenance: Codable, Equatable {
    let source: String
    let collectedAt: Date
    let provider: String?
    let resolver: String?
    let resultSource: LookupResultSource
}

enum LookupResultSource: String, Codable {
    case live
    case cached
    case mixed
    case snapshot

    var label: String {
        switch self {
        case .live:
            return "Live"
        case .cached:
            return "Cached"
        case .mixed:
            return "Mixed"
        case .snapshot:
            return "Snapshot"
        }
    }
}

enum LookupSectionKind: String, Codable, CaseIterable {
    case dns
    case availability
    case ssl
    case hsts
    case httpHeaders
    case reachability
    case ipGeolocation
    case emailSecurity
    case ownership
    case ptr
    case redirectChain
    case subdomains
    case portScan
    case suggestions
}

enum DomainAvailabilityStatus: String, Codable {
    case available
    case registered
    case unknown
}

struct DomainAvailabilityResult: Codable {
    let domain: String
    let status: DomainAvailabilityStatus
}

struct DomainSuggestionResult: Identifiable, Codable {
    let id: UUID
    let domain: String
    let status: DomainAvailabilityStatus

    init(id: UUID = UUID(), domain: String, status: DomainAvailabilityStatus) {
        self.id = id
        self.domain = domain
        self.status = status
    }
}

struct WatchedDomain: Codable, Identifiable {
    let id: UUID
    let domain: String
    let createdAt: Date
    var lastKnownAvailability: DomainAvailabilityStatus?

    init(
        id: UUID = UUID(),
        domain: String,
        createdAt: Date = Date(),
        lastKnownAvailability: DomainAvailabilityStatus? = nil
    ) {
        self.id = id
        self.domain = domain
        self.createdAt = createdAt
        self.lastKnownAvailability = lastKnownAvailability
    }
}

enum ChangeSeverity: Int, Codable, CaseIterable, Comparable {
    case low
    case medium
    case high

    static func < (lhs: ChangeSeverity, rhs: ChangeSeverity) -> Bool {
        lhs.rawValue < rhs.rawValue
    }

    var title: String {
        switch self {
        case .low:
            return "Low"
        case .medium:
            return "Medium"
        case .high:
            return "High"
        }
    }
}

enum CertificateWarningLevel: String, Codable {
    case none
    case warning
    case critical

    var title: String {
        switch self {
        case .none:
            return "Healthy"
        case .warning:
            return "Warning"
        case .critical:
            return "Critical"
        }
    }
}

struct DomainChangeSummary: Codable, Equatable {
    let hasChanges: Bool
    let changedSections: [String]
    let message: String
    let severity: ChangeSeverity
    let impactClassification: ChangeImpactClassification
    let generatedAt: Date
    let observedFacts: [String]
    let inferredConclusions: [String]
    let contextNote: String?
    let riskAssessment: DomainRiskAssessment?
    let insights: [String]
    let riskScoreDelta: Int?

    init(
        hasChanges: Bool,
        changedSections: [String],
        message: String,
        severity: ChangeSeverity,
        impactClassification: ChangeImpactClassification,
        generatedAt: Date,
        observedFacts: [String] = [],
        inferredConclusions: [String] = [],
        contextNote: String? = nil,
        riskAssessment: DomainRiskAssessment? = nil,
        insights: [String] = [],
        riskScoreDelta: Int? = nil
    ) {
        self.hasChanges = hasChanges
        self.changedSections = changedSections
        self.message = message
        self.severity = severity
        self.impactClassification = impactClassification
        self.generatedAt = generatedAt
        self.observedFacts = observedFacts
        self.inferredConclusions = inferredConclusions
        self.contextNote = contextNote
        self.riskAssessment = riskAssessment
        self.insights = insights
        self.riskScoreDelta = riskScoreDelta
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        hasChanges = try container.decodeIfPresent(Bool.self, forKey: .hasChanges) ?? false
        changedSections = try container.decodeIfPresent([String].self, forKey: .changedSections) ?? []
        generatedAt = try container.decode(Date.self, forKey: .generatedAt)
        severity = try container.decodeIfPresent(ChangeSeverity.self, forKey: .severity) ?? (hasChanges ? .medium : .low)
        impactClassification = try container.decodeIfPresent(ChangeImpactClassification.self, forKey: .impactClassification)
            ?? (severity == .high ? .critical : (hasChanges ? .warning : .informational))
        message = try container.decodeIfPresent(String.self, forKey: .message)
            ?? (changedSections.isEmpty ? "No meaningful changes" : changedSections.joined(separator: " • "))
        observedFacts = try container.decodeIfPresent([String].self, forKey: .observedFacts) ?? []
        inferredConclusions = try container.decodeIfPresent([String].self, forKey: .inferredConclusions) ?? []
        contextNote = try container.decodeIfPresent(String.self, forKey: .contextNote)
        riskAssessment = try container.decodeIfPresent(DomainRiskAssessment.self, forKey: .riskAssessment)
        insights = try container.decodeIfPresent([String].self, forKey: .insights) ?? []
        riskScoreDelta = try container.decodeIfPresent(Int.self, forKey: .riskScoreDelta)
    }
}

enum BatchLookupSource: String, Codable {
    case manual
    case watchlistRefresh
    case workflow
}

enum BatchLookupStatus: String, Codable {
    case pending
    case running
    case completed
    case failed
}

struct BatchLookupResult: Identifiable, Codable, Equatable {
    let id: UUID
    let domain: String
    let historyEntryID: UUID?
    let resultSource: LookupResultSource
    let availability: DomainAvailabilityStatus?
    let primaryIP: String?
    let quickStatus: String
    let summaryMessage: String?
    let changeSeverity: ChangeSeverity?
    let changeClassification: ChangeImpactClassification?
    let certificateWarningLevel: CertificateWarningLevel
    let riskScore: Int?
    let riskLevel: RiskLevel?
    let timestamp: Date
    let status: BatchLookupStatus
    let errorMessage: String?

    init(
        id: UUID = UUID(),
        domain: String,
        historyEntryID: UUID?,
        resultSource: LookupResultSource = .live,
        availability: DomainAvailabilityStatus?,
        primaryIP: String?,
        quickStatus: String,
        summaryMessage: String? = nil,
        changeSeverity: ChangeSeverity? = nil,
        changeClassification: ChangeImpactClassification? = nil,
        certificateWarningLevel: CertificateWarningLevel = .none,
        riskScore: Int? = nil,
        riskLevel: RiskLevel? = nil,
        timestamp: Date,
        status: BatchLookupStatus,
        errorMessage: String? = nil
    ) {
        self.id = id
        self.domain = domain
        self.historyEntryID = historyEntryID
        self.resultSource = resultSource
        self.availability = availability
        self.primaryIP = primaryIP
        self.quickStatus = quickStatus
        self.summaryMessage = summaryMessage
        self.changeSeverity = changeSeverity
        self.changeClassification = changeClassification
        self.certificateWarningLevel = certificateWarningLevel
        self.riskScore = riskScore
        self.riskLevel = riskLevel
        self.timestamp = timestamp
        self.status = status
        self.errorMessage = errorMessage
    }

    var hasMeaningfulChange: Bool {
        quickStatus == "Changed"
            || quickStatus == "High"
            || quickStatus == "Critical"
            || certificateWarningLevel != .none
            || riskLevel == .high
            || status == .failed
    }
}

struct BatchSweepSummary: Identifiable, Equatable {
    let id = UUID()
    let source: BatchLookupSource
    let totalDomains: Int
    let changedDomains: Int
    let unchangedDomains: Int
    let warningDomains: Int
    let results: [BatchLookupResult]
    let generatedAt: Date
}

struct DomainWorkflow: Codable, Identifiable, Equatable {
    let id: UUID
    var name: String
    var domains: [String]
    var createdAt: Date
    var updatedAt: Date
    var notes: String?
    var collaboration: CollaborationMetadata?

    init(
        id: UUID = UUID(),
        name: String,
        domains: [String],
        createdAt: Date = Date(),
        updatedAt: Date = Date(),
        notes: String? = nil,
        collaboration: CollaborationMetadata? = nil
    ) {
        self.id = id
        self.name = name
        self.domains = domains
        self.createdAt = createdAt
        self.updatedAt = updatedAt
        self.notes = notes
        self.collaboration = collaboration
    }
}

struct WorkflowRunSummary: Identifiable, Equatable {
    let id = UUID()
    let workflowID: UUID
    let workflowName: String
    let totalDomains: Int
    let changedDomains: Int
    let unchangedDomains: Int
    let warningDomains: Int
    let results: [BatchLookupResult]
    let workflowInsights: [WorkflowInsight]
    let generatedAt: Date
}

enum DataCapability: String, Codable {
    case ownershipHistory
    case dnsHistory
    case extendedSubdomains
    case domainPricing
}

enum UsageCreditFeature: String, Codable, CaseIterable, Identifiable, Sendable {
    case ownershipHistory
    case dnsHistory
    case extendedSubdomains

    nonisolated var id: String { rawValue }

    nonisolated var title: String {
        switch self {
        case .ownershipHistory:
            return "Ownership history"
        case .dnsHistory:
            return "DNS history"
        case .extendedSubdomains:
            return "Extended subdomains"
        }
    }

    nonisolated var defaultAllowance: Int {
        switch self {
        case .ownershipHistory, .dnsHistory:
            return 8
        case .extendedSubdomains:
            return 12
        }
    }
}

struct UsageCreditStatus: Codable, Equatable, Sendable {
    let feature: UsageCreditFeature
    let remaining: Int
    let total: Int
    let resetContext: String

    nonisolated var summary: String {
        "\(remaining) uses remaining"
    }

    nonisolated var isExhausted: Bool {
        remaining <= 0
    }
}

struct DomainOwnershipHistoryEvent: Identifiable, Codable, Equatable, Sendable {
    let id: UUID
    let date: Date
    let summary: String
    let registrar: String?
    let registrant: String?
    let nameservers: [String]
    let source: String
    let isExternal: Bool

    nonisolated init(
        id: UUID = UUID(),
        date: Date,
        summary: String,
        registrar: String? = nil,
        registrant: String? = nil,
        nameservers: [String] = [],
        source: String,
        isExternal: Bool
    ) {
        self.id = id
        self.date = date
        self.summary = summary
        self.registrar = registrar
        self.registrant = registrant
        self.nameservers = nameservers
        self.source = source
        self.isExternal = isExternal
    }
}

struct DNSHistoryEvent: Identifiable, Codable, Equatable, Sendable {
    let id: UUID
    let date: Date
    let summary: String
    let aRecords: [String]
    let nameservers: [String]
    let source: String
    let isExternal: Bool

    nonisolated init(
        id: UUID = UUID(),
        date: Date,
        summary: String,
        aRecords: [String] = [],
        nameservers: [String] = [],
        source: String,
        isExternal: Bool
    ) {
        self.id = id
        self.date = date
        self.summary = summary
        self.aRecords = aRecords
        self.nameservers = nameservers
        self.source = source
        self.isExternal = isExternal
    }
}

struct DomainPricingInsight: Codable, Equatable, Sendable {
    let estimatedPrice: String?
    let premiumIndicator: Bool?
    let resaleSignal: String?
    let auctionSignal: String?
    let source: String
    let collectedAt: Date
}

enum HistoryDateFilter: String, CaseIterable, Identifiable {
    case today
    case last7Days
    case all

    var id: String { rawValue }

    var title: String {
        switch self {
        case .today:
            return "Today"
        case .last7Days:
            return "Last 7 Days"
        case .all:
            return "All"
        }
    }
}

enum ChangeFilterOption: String, CaseIterable, Identifiable {
    case all
    case changed
    case unchanged

    var id: String { rawValue }

    var title: String {
        switch self {
        case .all:
            return "All"
        case .changed:
            return "Changed"
        case .unchanged:
            return "Unchanged"
        }
    }
}

enum HistorySortOption: String, CaseIterable, Identifiable {
    case newest
    case oldest
    case domain

    var id: String { rawValue }

    var title: String {
        switch self {
        case .newest:
            return "Newest"
        case .oldest:
            return "Oldest"
        case .domain:
            return "Domain A-Z"
        }
    }
}

enum TimelineGroupingOption: String, CaseIterable, Identifiable {
    case none
    case relativeDay

    var id: String { rawValue }

    var title: String {
        switch self {
        case .none:
            return "Ungrouped"
        case .relativeDay:
            return "Today / Yesterday / Older"
        }
    }
}

enum HistoryAutoPruneOption: String, CaseIterable, Codable, Identifiable {
    case keep50
    case keep100
    case unlimited

    var id: String { rawValue }

    var title: String {
        switch self {
        case .keep50:
            return "Keep Last 50"
        case .keep100:
            return "Keep Last 100"
        case .unlimited:
            return "Unlimited"
        }
    }

    var keepCount: Int? {
        switch self {
        case .keep50:
            return 50
        case .keep100:
            return 100
        case .unlimited:
            return nil
        }
    }
}

struct SnapshotSummary: Identifiable, Codable, Equatable {
    let id: UUID
    let domain: String
    let timestamp: Date
    let trackedDomainID: UUID?
    let snapshotIndex: Int?
    let previousSnapshotID: UUID?
    let changeCount: Int
    let severitySummary: ChangeSeverity?
    let changeSummaryMessage: String?
    let availability: DomainAvailabilityStatus?
    let primaryIP: String?
    let tlsStatus: String?
    let riskScore: Int?
    let historyEntryID: UUID

    var hasChanges: Bool {
        changeCount > 0
    }
}

struct FullSnapshot: Codable {
    let historyEntry: HistoryEntry
}

struct TimelineSection: Identifiable, Equatable {
    let id: String
    let title: String
    let entries: [SnapshotSummary]
}

enum WatchlistFilterOption: String, CaseIterable, Identifiable {
    case all
    case pinnedOnly
    case changedOnly

    var id: String { rawValue }

    var title: String {
        switch self {
        case .all:
            return "All"
        case .pinnedOnly:
            return "Pinned Only"
        case .changedOnly:
            return "Changed Only"
        }
    }
}

enum WatchlistSortOption: String, CaseIterable, Identifiable {
    case pinned
    case recentlyUpdated
    case alphabetical

    var id: String { rawValue }

    var title: String {
        switch self {
        case .pinned:
            return "Pinned"
        case .recentlyUpdated:
            return "Recently Updated"
        case .alphabetical:
            return "Alphabetical"
        }
    }
}

enum PremiumCapability: String, Codable {
    case unlimitedTrackedDomains
    case automatedMonitoring
    case pushAlerts
    case batchTracking
    case advancedExports
}

enum CollaborationPermission: String, Codable, Equatable {
    case readOnly
    case editable

    var title: String {
        switch self {
        case .readOnly:
            return "Read only"
        case .editable:
            return "Editable"
        }
    }
}

enum CollaborationOwnership: String, Codable, Equatable {
    case owner
    case participant

    var title: String {
        switch self {
        case .owner:
            return "Owned by you"
        case .participant:
            return "Shared with you"
        }
    }
}

enum CollaborationScope: String, Codable, Equatable {
    case privateDatabase
    case sharedDatabase
}

struct CollaborationMetadata: Codable, Equatable {
    var scope: CollaborationScope
    var ownership: CollaborationOwnership
    var permission: CollaborationPermission
    var shareRecordName: String?

    init(
        scope: CollaborationScope,
        ownership: CollaborationOwnership,
        permission: CollaborationPermission,
        shareRecordName: String? = nil
    ) {
        self.scope = scope
        self.ownership = ownership
        self.permission = permission
        self.shareRecordName = shareRecordName
    }

    var isShared: Bool {
        shareRecordName != nil || scope == .sharedDatabase
    }

    var canEdit: Bool {
        permission == .editable
    }

    var isOwner: Bool {
        ownership == .owner
    }
}

enum MonitoringSensitivity: String, Codable, CaseIterable, Identifiable, Sendable {
    case low
    case medium
    case high

    var id: String { rawValue }

    var title: String {
        rawValue.capitalized
    }

    var minimumInterval: TimeInterval {
        switch self {
        case .low:
            return 30 * 60
        case .medium:
            return 15 * 60
        case .high:
            return 5 * 60
        }
    }

    var intervalMultiplier: Double {
        switch self {
        case .low:
            return 1.5
        case .medium:
            return 1.25
        case .high:
            return 1.1
        }
    }
}

struct QuietHours: Codable, Equatable, Sendable {
    var startHour: Int
    var endHour: Int

    init(startHour: Int, endHour: Int) {
        self.startHour = max(0, min(23, startHour))
        self.endHour = max(0, min(23, endHour))
    }

    func contains(_ date: Date, calendar: Calendar = .current) -> Bool {
        let hour = calendar.component(.hour, from: date)
        if startHour <= endHour {
            return hour >= startHour && hour < endHour
        }
        return hour >= startHour || hour < endHour
    }
}

enum MonitoringBaseInterval: String, Codable, CaseIterable, Identifiable {
    case thirtyMinutes
    case hourly
    case sixHours
    case twelveHours
    case daily

    var id: String { rawValue }

    var title: String {
        switch self {
        case .thirtyMinutes:
            return "Every 30 Minutes"
        case .hourly:
            return "Hourly"
        case .sixHours:
            return "Every 6 Hours"
        case .twelveHours:
            return "Every 12 Hours"
        case .daily:
            return "Daily"
        }
    }

    var interval: TimeInterval {
        switch self {
        case .thirtyMinutes:
            return 30 * 60
        case .hourly:
            return 60 * 60
        case .sixHours:
            return 6 * 60 * 60
        case .twelveHours:
            return 12 * 60 * 60
        case .daily:
            return 24 * 60 * 60
        }
    }

    static func nearest(to interval: TimeInterval) -> MonitoringBaseInterval {
        allCases.min { abs($0.interval - interval) < abs($1.interval - interval) } ?? .twelveHours
    }
}

struct MonitoringConfig: Codable, Equatable, Sendable {
    var isEnabled: Bool
    var baseInterval: TimeInterval
    var adaptiveEnabled: Bool
    var sensitivity: MonitoringSensitivity
    var quietHours: QuietHours?

    init(
        isEnabled: Bool = false,
        baseInterval: TimeInterval = MonitoringBaseInterval.twelveHours.interval,
        adaptiveEnabled: Bool = true,
        sensitivity: MonitoringSensitivity = .medium,
        quietHours: QuietHours? = nil
    ) {
        self.isEnabled = isEnabled
        self.baseInterval = baseInterval
        self.adaptiveEnabled = adaptiveEnabled
        self.sensitivity = sensitivity
        self.quietHours = quietHours
    }

    var maxInterval: TimeInterval {
        24 * 60 * 60
    }

    var sanitizedBaseInterval: TimeInterval {
        max(5 * 60, min(baseInterval, maxInterval))
    }
}

struct MonitoringState: Codable, Equatable, Sendable {
    var lastCheck: Date?
    var lastChangeHash: String?
    var lastAlertDate: Date?
    var consecutiveStableChecks: Int
    var currentInterval: TimeInterval
    var lastChangeDate: Date?

    init(
        lastCheck: Date? = nil,
        lastChangeHash: String? = nil,
        lastAlertDate: Date? = nil,
        consecutiveStableChecks: Int = 0,
        currentInterval: TimeInterval = 0,
        lastChangeDate: Date? = nil
    ) {
        self.lastCheck = lastCheck
        self.lastChangeHash = lastChangeHash
        self.lastAlertDate = lastAlertDate
        self.consecutiveStableChecks = consecutiveStableChecks
        self.currentInterval = currentInterval
        self.lastChangeDate = lastChangeDate
    }
}

struct MonitoringPendingAlert: Codable, Identifiable, Equatable, Sendable {
    let id: UUID
    var detectedAt: Date
    var message: String
    var severity: MonitoringAlertSeverity
    var changeHash: String

    init(
        id: UUID = UUID(),
        detectedAt: Date,
        message: String,
        severity: MonitoringAlertSeverity,
        changeHash: String
    ) {
        self.id = id
        self.detectedAt = detectedAt
        self.message = message
        self.severity = severity
        self.changeHash = changeHash
    }
}

struct TrackedDomain: Codable, Identifiable, Equatable {
    let id: UUID
    var domain: String
    var createdAt: Date
    var updatedAt: Date
    var note: String?
    var isPinned: Bool
    var monitoringEnabled: Bool
    var lastKnownAvailability: DomainAvailabilityStatus?
    var lastSnapshotID: UUID?
    var lastChangeSummary: DomainChangeSummary?
    var lastChangeSeverity: ChangeSeverity?
    var certificateWarningLevel: CertificateWarningLevel
    var certificateDaysRemaining: Int?
    var lastMonitoredAt: Date?
    var lastAlertAt: Date?
    var monitoringState: MonitoringState
    var pendingMonitoringAlerts: [MonitoringPendingAlert]
    var collaboration: CollaborationMetadata?

    init(
        id: UUID = UUID(),
        domain: String,
        createdAt: Date = Date(),
        updatedAt: Date = Date(),
        note: String? = nil,
        isPinned: Bool = false,
        monitoringEnabled: Bool = true,
        lastKnownAvailability: DomainAvailabilityStatus? = nil,
        lastSnapshotID: UUID? = nil,
        lastChangeSummary: DomainChangeSummary? = nil,
        lastChangeSeverity: ChangeSeverity? = nil,
        certificateWarningLevel: CertificateWarningLevel = .none,
        certificateDaysRemaining: Int? = nil,
        lastMonitoredAt: Date? = nil,
        lastAlertAt: Date? = nil,
        monitoringState: MonitoringState = MonitoringState(),
        pendingMonitoringAlerts: [MonitoringPendingAlert] = [],
        collaboration: CollaborationMetadata? = nil
    ) {
        self.id = id
        self.domain = domain
        self.createdAt = createdAt
        self.updatedAt = updatedAt
        self.note = note
        self.isPinned = isPinned
        self.monitoringEnabled = monitoringEnabled
        self.lastKnownAvailability = lastKnownAvailability
        self.lastSnapshotID = lastSnapshotID
        self.lastChangeSummary = lastChangeSummary
        self.lastChangeSeverity = lastChangeSeverity
        self.certificateWarningLevel = certificateWarningLevel
        self.certificateDaysRemaining = certificateDaysRemaining
        self.lastMonitoredAt = lastMonitoredAt
        self.lastAlertAt = lastAlertAt
        self.monitoringState = monitoringState
        self.pendingMonitoringAlerts = pendingMonitoringAlerts
        self.collaboration = collaboration
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
        domain = try container.decode(String.self, forKey: .domain)
        createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? Date()
        updatedAt = try container.decodeIfPresent(Date.self, forKey: .updatedAt) ?? createdAt
        note = try container.decodeIfPresent(String.self, forKey: .note)
        isPinned = try container.decodeIfPresent(Bool.self, forKey: .isPinned) ?? false
        monitoringEnabled = try container.decodeIfPresent(Bool.self, forKey: .monitoringEnabled) ?? true
        lastKnownAvailability = try container.decodeIfPresent(DomainAvailabilityStatus.self, forKey: .lastKnownAvailability)
        lastSnapshotID = try container.decodeIfPresent(UUID.self, forKey: .lastSnapshotID)
        lastChangeSummary = try container.decodeIfPresent(DomainChangeSummary.self, forKey: .lastChangeSummary)
        lastChangeSeverity = try container.decodeIfPresent(ChangeSeverity.self, forKey: .lastChangeSeverity) ?? lastChangeSummary?.severity
        certificateWarningLevel = try container.decodeIfPresent(CertificateWarningLevel.self, forKey: .certificateWarningLevel) ?? .none
        certificateDaysRemaining = try container.decodeIfPresent(Int.self, forKey: .certificateDaysRemaining)
        lastMonitoredAt = try container.decodeIfPresent(Date.self, forKey: .lastMonitoredAt)
        lastAlertAt = try container.decodeIfPresent(Date.self, forKey: .lastAlertAt)
        monitoringState = try container.decodeIfPresent(MonitoringState.self, forKey: .monitoringState) ?? MonitoringState()
        pendingMonitoringAlerts = try container.decodeIfPresent([MonitoringPendingAlert].self, forKey: .pendingMonitoringAlerts) ?? []
        collaboration = try container.decodeIfPresent(CollaborationMetadata.self, forKey: .collaboration)
    }
}

enum MonitoringScope: String, Codable, CaseIterable, Identifiable {
    case allTracked
    case selectedOnly

    var id: String { rawValue }

    var title: String {
        switch self {
        case .allTracked:
            return "All Tracked"
        case .selectedOnly:
            return "Selected Only"
        }
    }
}

enum MonitoringAlertSeverity: Int, Codable, CaseIterable, Comparable {
    case info
    case warning
    case critical

    static func < (lhs: MonitoringAlertSeverity, rhs: MonitoringAlertSeverity) -> Bool {
        lhs.rawValue < rhs.rawValue
    }

    var title: String {
        switch self {
        case .info:
            return "Info"
        case .warning:
            return "Warning"
        case .critical:
            return "Critical"
        }
    }
}

enum MonitoringAlertFilter: String, Codable, CaseIterable, Identifiable {
    case criticalOnly
    case criticalAndWarnings
    case allChanges

    var id: String { rawValue }

    var title: String {
        switch self {
        case .criticalOnly:
            return "Critical Only"
        case .criticalAndWarnings:
            return "Critical + Warnings"
        case .allChanges:
            return "All Changes"
        }
    }

    var minimumSeverity: MonitoringAlertSeverity {
        switch self {
        case .criticalOnly:
            return .critical
        case .criticalAndWarnings:
            return .warning
        case .allChanges:
            return .info
        }
    }
}

enum MonitoringRunTrigger: String, Codable {
    case manual
    case background
    case cli

    var title: String {
        switch self {
        case .manual:
            return "Manual"
        case .background:
            return "Background"
        case .cli:
            return "CLI"
        }
    }
}

struct MonitoringSettings: Codable, Equatable {
    private enum CodingKeys: String, CodingKey {
        case config
        case isEnabled
        case frequency
        case scope
        case selectedDomainIDs
        case alertFilter
        case alertsEnabled
    }

    var config: MonitoringConfig
    var scope: MonitoringScope
    var selectedDomainIDs: [UUID]
    var alertFilter: MonitoringAlertFilter
    var alertsEnabled: Bool

    init(
        config: MonitoringConfig = MonitoringConfig(),
        scope: MonitoringScope = .allTracked,
        selectedDomainIDs: [UUID] = [],
        alertFilter: MonitoringAlertFilter = .criticalAndWarnings,
        alertsEnabled: Bool = false
    ) {
        self.config = config
        self.scope = scope
        self.selectedDomainIDs = selectedDomainIDs
        self.alertFilter = alertFilter
        self.alertsEnabled = alertsEnabled
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let legacyEnabled = try container.decodeIfPresent(Bool.self, forKey: .isEnabled) ?? false
        let legacyFrequencyRaw = try container.decodeIfPresent(String.self, forKey: .frequency)

        if let decodedConfig = try container.decodeIfPresent(MonitoringConfig.self, forKey: .config) {
            config = decodedConfig
        } else {
            let mappedInterval: TimeInterval
            switch legacyFrequencyRaw {
            case "daily":
                mappedInterval = MonitoringBaseInterval.daily.interval
            case "twiceDaily":
                mappedInterval = MonitoringBaseInterval.twelveHours.interval
            default:
                mappedInterval = MonitoringBaseInterval.twelveHours.interval
            }

            config = MonitoringConfig(
                isEnabled: legacyEnabled,
                baseInterval: mappedInterval,
                adaptiveEnabled: true,
                sensitivity: .medium,
                quietHours: nil
            )
        }

        scope = try container.decodeIfPresent(MonitoringScope.self, forKey: .scope) ?? .allTracked
        selectedDomainIDs = try container.decodeIfPresent([UUID].self, forKey: .selectedDomainIDs) ?? []
        alertFilter = try container.decodeIfPresent(MonitoringAlertFilter.self, forKey: .alertFilter) ?? .criticalAndWarnings
        alertsEnabled = try container.decodeIfPresent(Bool.self, forKey: .alertsEnabled) ?? false
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(config, forKey: .config)
        try container.encode(scope, forKey: .scope)
        try container.encode(selectedDomainIDs, forKey: .selectedDomainIDs)
        try container.encode(alertFilter, forKey: .alertFilter)
        try container.encode(alertsEnabled, forKey: .alertsEnabled)
    }

    var isEnabled: Bool {
        get { config.isEnabled }
        set { config.isEnabled = newValue }
    }

    var baseInterval: TimeInterval {
        get { config.baseInterval }
        set { config.baseInterval = newValue }
    }

    var adaptiveEnabled: Bool {
        get { config.adaptiveEnabled }
        set { config.adaptiveEnabled = newValue }
    }

    var sensitivity: MonitoringSensitivity {
        get { config.sensitivity }
        set { config.sensitivity = newValue }
    }

    var quietHours: QuietHours? {
        get { config.quietHours }
        set { config.quietHours = newValue }
    }
}

struct MonitoringDomainResult: Codable, Identifiable, Equatable {
    let id: UUID
    let domain: String
    let historyEntryID: UUID?
    let checkedAt: Date
    let didChange: Bool
    let summaryMessage: String
    let alertSeverity: MonitoringAlertSeverity?
    let certificateWarningLevel: CertificateWarningLevel
    let resultSource: LookupResultSource
    let errorMessage: String?

    init(
        id: UUID = UUID(),
        domain: String,
        historyEntryID: UUID?,
        checkedAt: Date,
        didChange: Bool,
        summaryMessage: String,
        alertSeverity: MonitoringAlertSeverity?,
        certificateWarningLevel: CertificateWarningLevel,
        resultSource: LookupResultSource,
        errorMessage: String? = nil
    ) {
        self.id = id
        self.domain = domain
        self.historyEntryID = historyEntryID
        self.checkedAt = checkedAt
        self.didChange = didChange
        self.summaryMessage = summaryMessage
        self.alertSeverity = alertSeverity
        self.certificateWarningLevel = certificateWarningLevel
        self.resultSource = resultSource
        self.errorMessage = errorMessage
    }
}

struct MonitoringLog: Codable, Identifiable, Equatable {
    let id: UUID
    let timestamp: Date
    let trigger: MonitoringRunTrigger
    let domainsChecked: Int
    let changesFound: Int
    let alertsTriggered: Int
    let checkedDomains: [MonitoringDomainResult]
    let errors: [String]

    init(
        id: UUID = UUID(),
        timestamp: Date,
        trigger: MonitoringRunTrigger,
        domainsChecked: Int,
        changesFound: Int,
        alertsTriggered: Int,
        checkedDomains: [MonitoringDomainResult],
        errors: [String] = []
    ) {
        self.id = id
        self.timestamp = timestamp
        self.trigger = trigger
        self.domainsChecked = domainsChecked
        self.changesFound = changesFound
        self.alertsTriggered = alertsTriggered
        self.checkedDomains = checkedDomains
        self.errors = errors
    }

    var summary: String {
        if errors.isEmpty {
            return "\(changesFound) changes across \(domainsChecked) domains"
        }
        return "\(changesFound) changes, \(errors.count) errors"
    }
}

// MARK: - DNS Models

enum DNSRecordType: String, CaseIterable, Codable {
    case A
    case AAAA
    case MX
    case NS
    case TXT
    case CNAME
    case SOA
    case SRV
    case CAA
    case DS
    case PTR

    var queryType: Int {
        switch self {
        case .A: return 1
        case .AAAA: return 28
        case .MX: return 15
        case .NS: return 2
        case .TXT: return 16
        case .CNAME: return 5
        case .SOA: return 6
        case .SRV: return 33
        case .CAA: return 257
        case .DS: return 43
        case .PTR: return 12
        }
    }

    var usesRawDataValue: Bool {
        switch self {
        case .TXT, .SOA, .DS:
            return true
        default:
            return false
        }
    }
}

struct DNSRecord: Identifiable, Codable {
    var id = UUID()
    let value: String
    let ttl: Int
}

struct DNSSection: Identifiable, Codable {
    var id = UUID()
    let recordType: DNSRecordType
    var records: [DNSRecord]
    var wildcardRecords: [DNSRecord] = []
    var dnssecSigned: Bool?
    var error: String?
}

// MARK: - SSL Models

struct SSLCertificateInfo: Codable {
    struct CertChainEntry: Codable {
        let subject: String
        let issuer: String
    }

    let commonName: String
    let subjectAltNames: [String]
    let issuer: String
    let validFrom: Date
    let validUntil: Date
    let daysUntilExpiry: Int
    let chainDepth: Int
    let tlsVersion: String?
    let cipherSuite: String?
    let chain: [CertChainEntry]

    init(
        commonName: String,
        subjectAltNames: [String],
        issuer: String,
        validFrom: Date,
        validUntil: Date,
        daysUntilExpiry: Int,
        chainDepth: Int,
        tlsVersion: String? = nil,
        cipherSuite: String? = nil,
        chain: [CertChainEntry] = []
    ) {
        self.commonName = commonName
        self.subjectAltNames = subjectAltNames
        self.issuer = issuer
        self.validFrom = validFrom
        self.validUntil = validUntil
        self.daysUntilExpiry = daysUntilExpiry
        self.chainDepth = chainDepth
        self.tlsVersion = tlsVersion
        self.cipherSuite = cipherSuite
        self.chain = chain
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        commonName = try container.decode(String.self, forKey: .commonName)
        subjectAltNames = try container.decode([String].self, forKey: .subjectAltNames)
        issuer = try container.decode(String.self, forKey: .issuer)
        validFrom = try container.decode(Date.self, forKey: .validFrom)
        validUntil = try container.decode(Date.self, forKey: .validUntil)
        daysUntilExpiry = try container.decode(Int.self, forKey: .daysUntilExpiry)
        chainDepth = try container.decode(Int.self, forKey: .chainDepth)
        tlsVersion = try container.decodeIfPresent(String.self, forKey: .tlsVersion)
        cipherSuite = try container.decodeIfPresent(String.self, forKey: .cipherSuite)
        chain = try container.decodeIfPresent([CertChainEntry].self, forKey: .chain) ?? []
    }
}

// MARK: - HTTP Headers Models

struct HTTPHeader: Identifiable, Codable {
    var id = UUID()
    let name: String
    let value: String

    static let securityHeaders: Set<String> = [
        "strict-transport-security",
        "x-frame-options",
        "x-content-type-options",
        "content-security-policy",
        "referrer-policy"
    ]

    var isSecurityHeader: Bool {
        Self.securityHeaders.contains(name.lowercased())
    }
}

// MARK: - Reachability Models

struct PortReachability: Identifiable, Codable {
    var id = UUID()
    let port: UInt16
    let reachable: Bool
    let latencyMs: Int?
}

// MARK: - IP Geolocation Models

struct IPGeolocation: Codable {
    let ip: String
    let city: String?
    let region: String?
    let country_name: String?
    let org: String?
    let latitude: Double?
    let longitude: Double?
}

// MARK: - Ownership Models

struct DomainOwnership: Codable, Equatable {
    let registrar: String?
    let registrant: String?
    let createdDate: Date?
    let expirationDate: Date?
    let status: [String]
    let nameservers: [String]
    let abuseEmail: String?

    init(
        registrar: String? = nil,
        registrant: String? = nil,
        createdDate: Date? = nil,
        expirationDate: Date? = nil,
        status: [String] = [],
        nameservers: [String] = [],
        abuseEmail: String? = nil
    ) {
        self.registrar = registrar
        self.registrant = registrant
        self.createdDate = createdDate
        self.expirationDate = expirationDate
        self.status = status
        self.nameservers = nameservers
        self.abuseEmail = abuseEmail
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        registrar = try container.decodeIfPresent(String.self, forKey: .registrar)
        registrant = try container.decodeIfPresent(String.self, forKey: .registrant)
        createdDate = try container.decodeIfPresent(Date.self, forKey: .createdDate)
        expirationDate = try container.decodeIfPresent(Date.self, forKey: .expirationDate)
        status = try container.decodeIfPresent([String].self, forKey: .status) ?? []
        nameservers = try container.decodeIfPresent([String].self, forKey: .nameservers) ?? []
        abuseEmail = try container.decodeIfPresent(String.self, forKey: .abuseEmail)
    }
}

struct DiscoveredSubdomain: Codable, Equatable, Hashable, Identifiable, Sendable {
    var id: String { hostname }
    let hostname: String
    let source: String?
    let isExtended: Bool

    nonisolated init(hostname: String, source: String? = nil, isExtended: Bool = false) {
        self.hostname = hostname
        self.source = source
        self.isExtended = isExtended
    }
}

// MARK: - Email Security Models

struct EmailSecurityResult: Codable {
    let spf: EmailSecurityRecord
    let dmarc: EmailSecurityRecord
    let dkim: EmailSecurityRecord
    let bimi: EmailSecurityRecord
    let mtaSts: MTASTSResult?

    init(
        spf: EmailSecurityRecord,
        dmarc: EmailSecurityRecord,
        dkim: EmailSecurityRecord,
        bimi: EmailSecurityRecord = EmailSecurityRecord(found: false, value: nil),
        mtaSts: MTASTSResult? = nil
    ) {
        self.spf = spf
        self.dmarc = dmarc
        self.dkim = dkim
        self.bimi = bimi
        self.mtaSts = mtaSts
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        spf = try container.decode(EmailSecurityRecord.self, forKey: .spf)
        dmarc = try container.decode(EmailSecurityRecord.self, forKey: .dmarc)
        dkim = try container.decode(EmailSecurityRecord.self, forKey: .dkim)
        bimi = try container.decodeIfPresent(EmailSecurityRecord.self, forKey: .bimi)
            ?? EmailSecurityRecord(found: false, value: nil)
        mtaSts = try container.decodeIfPresent(MTASTSResult.self, forKey: .mtaSts)
    }
}

struct EmailSecurityRecord: Codable {
    let found: Bool
    let value: String?
    let matchedSelector: String?

    init(found: Bool, value: String?, matchedSelector: String? = nil) {
        self.found = found
        self.value = value
        self.matchedSelector = matchedSelector
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        found = try container.decode(Bool.self, forKey: .found)
        value = try container.decodeIfPresent(String.self, forKey: .value)
        matchedSelector = try container.decodeIfPresent(String.self, forKey: .matchedSelector)
    }
}

struct MTASTSResult: Codable {
    let txtFound: Bool
    let policyMode: String?
}

// MARK: - Redirect Chain Models

struct RedirectHop: Identifiable, Codable {
    var id = UUID()
    let stepNumber: Int
    let statusCode: Int
    let url: String
    let isFinal: Bool
}

// MARK: - Port Scan Models

enum PortScanKind: String, Codable {
    case standard
    case custom
}

struct PortScanResult: Identifiable, Codable {
    var id = UUID()
    let port: UInt16
    let service: String
    let open: Bool
    var banner: String?
    let kind: PortScanKind
    let durationMs: Int?

    nonisolated init(
        port: UInt16,
        service: String,
        open: Bool,
        banner: String? = nil,
        kind: PortScanKind = .standard,
        durationMs: Int? = nil
    ) {
        self.port = port
        self.service = service
        self.open = open
        self.banner = banner
        self.kind = kind
        self.durationMs = durationMs
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
        port = try container.decode(UInt16.self, forKey: .port)
        service = try container.decode(String.self, forKey: .service)
        open = try container.decode(Bool.self, forKey: .open)
        banner = try container.decodeIfPresent(String.self, forKey: .banner)
        kind = try container.decodeIfPresent(PortScanKind.self, forKey: .kind) ?? .standard
        durationMs = try container.decodeIfPresent(Int.self, forKey: .durationMs)
    }
}

// MARK: - History Models

struct HistoryEntry: Identifiable, Codable {
    var id = UUID()
    let domain: String
    let timestamp: Date
    var trackedDomainID: UUID?
    var note: String?
    let dnsSections: [DNSSection]
    let sslInfo: SSLCertificateInfo?
    let httpHeaders: [HTTPHeader]
    let reachabilityResults: [PortReachability]
    let ipGeolocation: IPGeolocation?
    var emailSecurity: EmailSecurityResult?
    var mtaSts: MTASTSResult?
    var ownership: DomainOwnership?
    var ownershipHistory: [DomainOwnershipHistoryEvent]
    var ptrRecord: String?
    var redirectChain: [RedirectHop]
    var subdomains: [DiscoveredSubdomain]
    var extendedSubdomains: [DiscoveredSubdomain]
    var dnsHistory: [DNSHistoryEvent]
    var domainPricing: DomainPricingInsight?
    var portScanResults: [PortScanResult]
    var hstsPreloaded: Bool?
    var availabilityResult: DomainAvailabilityResult?
    var suggestions: [DomainSuggestionResult]
    var appVersion: String
    var resultSource: LookupResultSource
    var dataSources: [String]
    var provenanceBySection: [LookupSectionKind: SectionProvenance]
    var availabilityConfidence: ConfidenceLevel?
    var ownershipConfidence: ConfidenceLevel?
    var subdomainConfidence: ConfidenceLevel?
    var emailSecurityConfidence: ConfidenceLevel?
    var geolocationConfidence: ConfidenceLevel?
    var errorDetails: [LookupSectionKind: InspectionFailure]
    var isPartialSnapshot: Bool
    var validationIssues: [String]
    var resolverDisplayName: String
    var resolverURLString: String
    var totalLookupDurationMs: Int?
    var primaryIP: String?
    var finalRedirectURL: String?
    var tlsStatusSummary: String?
    var emailSecuritySummary: String?
    var httpGradeSummary: String?
    var changeSummary: DomainChangeSummary?
    var snapshotIndex: Int?
    var previousSnapshotID: UUID?
    var changeCount: Int
    var severitySummary: ChangeSeverity?
    var sslError: String?
    var httpHeadersError: String?
    var reachabilityError: String?
    var ipGeolocationError: String?
    var emailSecurityError: String?
    var ownershipError: String?
    var ownershipHistoryError: String?
    var ptrError: String?
    var redirectChainError: String?
    var subdomainsError: String?
    var extendedSubdomainsError: String?
    var dnsHistoryError: String?
    var domainPricingError: String?
    var portScanError: String?

    init(domain: String, timestamp: Date, trackedDomainID: UUID? = nil, note: String? = nil, dnsSections: [DNSSection],
         sslInfo: SSLCertificateInfo?, httpHeaders: [HTTPHeader],
         reachabilityResults: [PortReachability], ipGeolocation: IPGeolocation?,
         emailSecurity: EmailSecurityResult? = nil, mtaSts: MTASTSResult? = nil, ownership: DomainOwnership? = nil,
         ownershipHistory: [DomainOwnershipHistoryEvent] = [],
         ptrRecord: String? = nil, redirectChain: [RedirectHop] = [], subdomains: [DiscoveredSubdomain] = [],
         extendedSubdomains: [DiscoveredSubdomain] = [], dnsHistory: [DNSHistoryEvent] = [],
         domainPricing: DomainPricingInsight? = nil,
         portScanResults: [PortScanResult] = [],
         hstsPreloaded: Bool? = nil, availabilityResult: DomainAvailabilityResult? = nil,
         suggestions: [DomainSuggestionResult] = [], appVersion: String = "2.7.0",
         resultSource: LookupResultSource = .snapshot, dataSources: [String] = [],
         provenanceBySection: [LookupSectionKind: SectionProvenance] = [:],
         availabilityConfidence: ConfidenceLevel? = nil, ownershipConfidence: ConfidenceLevel? = nil,
         subdomainConfidence: ConfidenceLevel? = nil, emailSecurityConfidence: ConfidenceLevel? = nil,
         geolocationConfidence: ConfidenceLevel? = nil,
         errorDetails: [LookupSectionKind: InspectionFailure] = [:], isPartialSnapshot: Bool = false,
         validationIssues: [String] = [], resolverDisplayName: String, resolverURLString: String,
         totalLookupDurationMs: Int? = nil, primaryIP: String? = nil, finalRedirectURL: String? = nil,
         tlsStatusSummary: String? = nil, emailSecuritySummary: String? = nil, httpGradeSummary: String? = nil,
         changeSummary: DomainChangeSummary? = nil, snapshotIndex: Int? = nil, previousSnapshotID: UUID? = nil,
         changeCount: Int = 0, severitySummary: ChangeSeverity? = nil, sslError: String? = nil, httpHeadersError: String? = nil,
         reachabilityError: String? = nil, ipGeolocationError: String? = nil,
         emailSecurityError: String? = nil, ownershipError: String? = nil, ownershipHistoryError: String? = nil,
         ptrError: String? = nil, redirectChainError: String? = nil, subdomainsError: String? = nil,
         extendedSubdomainsError: String? = nil, dnsHistoryError: String? = nil,
         domainPricingError: String? = nil, portScanError: String? = nil) {
        self.domain = domain
        self.timestamp = timestamp
        self.trackedDomainID = trackedDomainID
        self.note = note
        self.dnsSections = dnsSections
        self.sslInfo = sslInfo
        self.httpHeaders = httpHeaders
        self.reachabilityResults = reachabilityResults
        self.ipGeolocation = ipGeolocation
        self.emailSecurity = emailSecurity
        self.mtaSts = mtaSts ?? emailSecurity?.mtaSts
        self.ownership = ownership
        self.ownershipHistory = ownershipHistory
        self.ptrRecord = ptrRecord
        self.redirectChain = redirectChain
        self.subdomains = subdomains
        self.extendedSubdomains = extendedSubdomains
        self.dnsHistory = dnsHistory
        self.domainPricing = domainPricing
        self.portScanResults = portScanResults
        self.hstsPreloaded = hstsPreloaded
        self.availabilityResult = availabilityResult
        self.suggestions = suggestions
        self.appVersion = appVersion
        self.resultSource = resultSource
        self.dataSources = dataSources
        self.provenanceBySection = provenanceBySection
        self.availabilityConfidence = availabilityConfidence
        self.ownershipConfidence = ownershipConfidence
        self.subdomainConfidence = subdomainConfidence
        self.emailSecurityConfidence = emailSecurityConfidence
        self.geolocationConfidence = geolocationConfidence
        self.errorDetails = errorDetails
        self.isPartialSnapshot = isPartialSnapshot
        self.validationIssues = validationIssues
        self.resolverDisplayName = resolverDisplayName
        self.resolverURLString = resolverURLString
        self.totalLookupDurationMs = totalLookupDurationMs
        self.primaryIP = primaryIP
        self.finalRedirectURL = finalRedirectURL
        self.tlsStatusSummary = tlsStatusSummary
        self.emailSecuritySummary = emailSecuritySummary
        self.httpGradeSummary = httpGradeSummary
        self.changeSummary = changeSummary
        self.snapshotIndex = snapshotIndex
        self.previousSnapshotID = previousSnapshotID
        self.changeCount = changeCount
        self.severitySummary = severitySummary
        self.sslError = sslError
        self.httpHeadersError = httpHeadersError
        self.reachabilityError = reachabilityError
        self.ipGeolocationError = ipGeolocationError
        self.emailSecurityError = emailSecurityError
        self.ownershipError = ownershipError
        self.ownershipHistoryError = ownershipHistoryError
        self.ptrError = ptrError
        self.redirectChainError = redirectChainError
        self.subdomainsError = subdomainsError
        self.extendedSubdomainsError = extendedSubdomainsError
        self.dnsHistoryError = dnsHistoryError
        self.domainPricingError = domainPricingError
        self.portScanError = portScanError
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
        domain = try container.decodeIfPresent(String.self, forKey: .domain) ?? "unknown-domain"
        timestamp = try container.decodeIfPresent(Date.self, forKey: .timestamp) ?? .distantPast
        trackedDomainID = try container.decodeIfPresent(UUID.self, forKey: .trackedDomainID)
        note = try container.decodeIfPresent(String.self, forKey: .note)
        dnsSections = try container.decodeIfPresent([DNSSection].self, forKey: .dnsSections) ?? []
        sslInfo = try container.decodeIfPresent(SSLCertificateInfo.self, forKey: .sslInfo)
        httpHeaders = try container.decodeIfPresent([HTTPHeader].self, forKey: .httpHeaders) ?? []
        reachabilityResults = try container.decodeIfPresent([PortReachability].self, forKey: .reachabilityResults) ?? []
        ipGeolocation = try container.decodeIfPresent(IPGeolocation.self, forKey: .ipGeolocation)
        emailSecurity = try container.decodeIfPresent(EmailSecurityResult.self, forKey: .emailSecurity)
        mtaSts = try container.decodeIfPresent(MTASTSResult.self, forKey: .mtaSts) ?? emailSecurity?.mtaSts
        ownership = try container.decodeIfPresent(DomainOwnership.self, forKey: .ownership)
        ownershipHistory = try container.decodeIfPresent([DomainOwnershipHistoryEvent].self, forKey: .ownershipHistory) ?? []
        ptrRecord = try container.decodeIfPresent(String.self, forKey: .ptrRecord)
        redirectChain = try container.decodeIfPresent([RedirectHop].self, forKey: .redirectChain) ?? []
        subdomains = try container.decodeIfPresent([DiscoveredSubdomain].self, forKey: .subdomains) ?? []
        extendedSubdomains = try container.decodeIfPresent([DiscoveredSubdomain].self, forKey: .extendedSubdomains) ?? []
        dnsHistory = try container.decodeIfPresent([DNSHistoryEvent].self, forKey: .dnsHistory) ?? []
        domainPricing = try container.decodeIfPresent(DomainPricingInsight.self, forKey: .domainPricing)
        portScanResults = try container.decodeIfPresent([PortScanResult].self, forKey: .portScanResults) ?? []
        hstsPreloaded = try container.decodeIfPresent(Bool.self, forKey: .hstsPreloaded)
        availabilityResult = try container.decodeIfPresent(DomainAvailabilityResult.self, forKey: .availabilityResult)
        suggestions = try container.decodeIfPresent([DomainSuggestionResult].self, forKey: .suggestions) ?? []
        appVersion = try container.decodeIfPresent(String.self, forKey: .appVersion) ?? "2.6.0"
        resultSource = try container.decodeIfPresent(LookupResultSource.self, forKey: .resultSource) ?? .snapshot
        dataSources = try container.decodeIfPresent([String].self, forKey: .dataSources) ?? []
        provenanceBySection = try container.decodeIfPresent([LookupSectionKind: SectionProvenance].self, forKey: .provenanceBySection) ?? [:]
        availabilityConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .availabilityConfidence)
        ownershipConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .ownershipConfidence)
        subdomainConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .subdomainConfidence)
        emailSecurityConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .emailSecurityConfidence)
        geolocationConfidence = try container.decodeIfPresent(ConfidenceLevel.self, forKey: .geolocationConfidence)
        errorDetails = try container.decodeIfPresent([LookupSectionKind: InspectionFailure].self, forKey: .errorDetails) ?? [:]
        validationIssues = try container.decodeIfPresent([String].self, forKey: .validationIssues) ?? HistoryEntry.defaultValidationIssues(domain: domain, timestamp: timestamp)
        isPartialSnapshot = try container.decodeIfPresent(Bool.self, forKey: .isPartialSnapshot) ?? !validationIssues.isEmpty
        resolverDisplayName = try container.decodeIfPresent(String.self, forKey: .resolverDisplayName) ?? "Cloudflare"
        resolverURLString = try container.decodeIfPresent(String.self, forKey: .resolverURLString) ?? DNSResolverOption.defaultURLString
        totalLookupDurationMs = try container.decodeIfPresent(Int.self, forKey: .totalLookupDurationMs)
        primaryIP = try container.decodeIfPresent(String.self, forKey: .primaryIP)
        finalRedirectURL = try container.decodeIfPresent(String.self, forKey: .finalRedirectURL)
        tlsStatusSummary = try container.decodeIfPresent(String.self, forKey: .tlsStatusSummary)
        emailSecuritySummary = try container.decodeIfPresent(String.self, forKey: .emailSecuritySummary)
        httpGradeSummary = try container.decodeIfPresent(String.self, forKey: .httpGradeSummary)
        changeSummary = try container.decodeIfPresent(DomainChangeSummary.self, forKey: .changeSummary)
        snapshotIndex = try container.decodeIfPresent(Int.self, forKey: .snapshotIndex)
        previousSnapshotID = try container.decodeIfPresent(UUID.self, forKey: .previousSnapshotID)
        changeCount = try container.decodeIfPresent(Int.self, forKey: .changeCount)
            ?? changeSummary?.changedSections.count
            ?? 0
        severitySummary = try container.decodeIfPresent(ChangeSeverity.self, forKey: .severitySummary)
            ?? changeSummary?.severity
        sslError = try container.decodeIfPresent(String.self, forKey: .sslError)
        httpHeadersError = try container.decodeIfPresent(String.self, forKey: .httpHeadersError)
        reachabilityError = try container.decodeIfPresent(String.self, forKey: .reachabilityError)
        ipGeolocationError = try container.decodeIfPresent(String.self, forKey: .ipGeolocationError)
        emailSecurityError = try container.decodeIfPresent(String.self, forKey: .emailSecurityError)
        ownershipError = try container.decodeIfPresent(String.self, forKey: .ownershipError)
        ownershipHistoryError = try container.decodeIfPresent(String.self, forKey: .ownershipHistoryError)
        ptrError = try container.decodeIfPresent(String.self, forKey: .ptrError)
        redirectChainError = try container.decodeIfPresent(String.self, forKey: .redirectChainError)
        subdomainsError = try container.decodeIfPresent(String.self, forKey: .subdomainsError)
        extendedSubdomainsError = try container.decodeIfPresent(String.self, forKey: .extendedSubdomainsError)
        dnsHistoryError = try container.decodeIfPresent(String.self, forKey: .dnsHistoryError)
        domainPricingError = try container.decodeIfPresent(String.self, forKey: .domainPricingError)
        portScanError = try container.decodeIfPresent(String.self, forKey: .portScanError)
    }

    private static func defaultValidationIssues(domain: String, timestamp: Date) -> [String] {
        var issues: [String] = []
        if domain == "unknown-domain" {
            issues.append("Missing domain in stored snapshot")
        }
        if timestamp == .distantPast {
            issues.append("Missing collection timestamp in stored snapshot")
        }
        return issues
    }

    var snapshotSummary: SnapshotSummary {
        SnapshotSummary(
            id: id,
            domain: domain,
            timestamp: timestamp,
            trackedDomainID: trackedDomainID,
            snapshotIndex: snapshotIndex,
            previousSnapshotID: previousSnapshotID,
            changeCount: changeCount,
            severitySummary: severitySummary ?? changeSummary?.severity,
            changeSummaryMessage: changeSummary?.message,
            availability: availabilityResult?.status,
            primaryIP: primaryIP,
            tlsStatus: tlsStatusSummary,
            riskScore: changeSummary?.riskAssessment?.score,
            historyEntryID: id
        )
    }
}

// MARK: - Cloudflare DNS-over-HTTPS Response

struct CloudflareDNSResponse: Decodable {
    let Status: Int
    let AD: Bool?
    let Answer: [CloudflareDNSAnswer]?

    struct CloudflareDNSAnswer: Decodable {
        let name: String
        let type: Int
        let TTL: Int
        let data: String
    }
}