aboutsummaryrefslogtreecommitdiff
path: root/DomainDig/Models.swift
blob: d83dc7907e19c70f9a300a341f68948db9e69f86 (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
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
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"
        }
    }
}

enum DomainHealth: String, Codable, Sendable, CaseIterable {
    case healthy
    case warning
    case critical

    var title: String {
        rawValue.capitalized
    }
}

struct PortfolioSnapshot: Codable, Sendable {
    var totalDomains: Int
    var healthyCount: Int
    var warningCount: Int
    var criticalCount: Int
    var changedLast24h: Int
    var expiringSoonCount: Int
    var unreachableCount: Int
}

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)
        let defaultImpact: ChangeImpactClassification
        if severity == .high {
            defaultImpact = .critical
        } else {
            defaultImpact = hasChanges ? .warning : .informational
        }
        impactClassification = try container.decodeIfPresent(ChangeImpactClassification.self, forKey: .impactClassification)
            ?? defaultImpact
        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
    case reputation
}

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 recordSnapshots: [DNSHistoryRecordSnapshot]
    let changedRecordTypes: [DNSRecordType]
    let source: String
    let isExternal: Bool

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

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
        date = try container.decode(Date.self, forKey: .date)
        summary = try container.decodeIfPresent(String.self, forKey: .summary) ?? "DNS change observed"
        aRecords = try container.decodeIfPresent([String].self, forKey: .aRecords) ?? []
        nameservers = try container.decodeIfPresent([String].self, forKey: .nameservers) ?? []
        let decodedRecordSnapshots = try container.decodeIfPresent([DNSHistoryRecordSnapshot].self, forKey: .recordSnapshots) ?? []
        if decodedRecordSnapshots.isEmpty {
            var synthesizedSnapshots: [DNSHistoryRecordSnapshot] = []
            if !aRecords.isEmpty {
                synthesizedSnapshots.append(DNSHistoryRecordSnapshot(recordType: .A, values: aRecords))
            }
            if !nameservers.isEmpty {
                synthesizedSnapshots.append(DNSHistoryRecordSnapshot(recordType: .NS, values: nameservers))
            }
            recordSnapshots = synthesizedSnapshots
        } else {
            recordSnapshots = decodedRecordSnapshots
        }
        changedRecordTypes = try container.decodeIfPresent([DNSRecordType].self, forKey: .changedRecordTypes)
            ?? recordSnapshots.map(\.recordType)
        source = try container.decodeIfPresent(String.self, forKey: .source) ?? "Unknown"
        isExternal = try container.decodeIfPresent(Bool.self, forKey: .isExternal) ?? false
    }
}

struct DNSHistoryRecordSnapshot: Identifiable, Codable, Sendable, Equatable {
    let id: UUID
    let recordType: DNSRecordType
    let values: [String]

    nonisolated init(id: UUID = UUID(), recordType: DNSRecordType, values: [String]) {
        self.id = id
        self.recordType = recordType
        self.values = values
    }

    static func == (lhs: DNSHistoryRecordSnapshot, rhs: DNSHistoryRecordSnapshot) -> Bool {
        lhs.recordType == rhs.recordType && lhs.values == rhs.values
    }
}

struct InferredProviderFingerprint: Codable, Equatable, Sendable {
    let name: String
    let confidence: ConfidenceLevel
    let evidence: [String]
}

enum DomainClassificationKind: String, Codable, CaseIterable, Sendable {
    case marketing
    case app
    case api
    case auth
    case docs
    case staticSite = "static"
    case infrastructure
    case status
    case unknown

    var title: String {
        if self == .staticSite {
            return "Static"
        }
        return rawValue.capitalized
    }
}

struct DomainClassificationSummary: Codable, Equatable, Sendable {
    let kind: DomainClassificationKind
    let confidence: ConfidenceLevel
    let reasons: [String]
}

struct OwnershipTransitionEvent: Identifiable, Codable, Equatable, Sendable {
    let id: UUID
    let date: Date
    let summary: String
    let previousRegistrar: String?
    let currentRegistrar: String?
    let previousRegistrant: String?
    let currentRegistrant: String?
    let previousNameservers: [String]
    let currentNameservers: [String]

    nonisolated init(
        id: UUID = UUID(),
        date: Date,
        summary: String,
        previousRegistrar: String? = nil,
        currentRegistrar: String? = nil,
        previousRegistrant: String? = nil,
        currentRegistrant: String? = nil,
        previousNameservers: [String] = [],
        currentNameservers: [String] = []
    ) {
        self.id = id
        self.date = date
        self.summary = summary
        self.previousRegistrar = previousRegistrar
        self.currentRegistrar = currentRegistrar
        self.previousRegistrant = previousRegistrant
        self.currentRegistrant = currentRegistrant
        self.previousNameservers = previousNameservers
        self.currentNameservers = currentNameservers
    }
}

struct HostingTransitionEvent: Identifiable, Codable, Equatable, Sendable {
    let id: UUID
    let date: Date
    let fromProvider: String
    let toProvider: String
    let summary: String

    nonisolated init(id: UUID = UUID(), date: Date, fromProvider: String, toProvider: String, summary: String) {
        self.id = id
        self.date = date
        self.fromProvider = fromProvider
        self.toProvider = toProvider
        self.summary = summary
    }
}

struct SubdomainHistoryEntry: Identifiable, Codable, Equatable, Sendable {
    let id: String
    let hostname: String
    let firstSeen: Date
    let lastSeen: Date
    let recurrenceCount: Int
    let statusChangeCount: Int
    let lastKnownStatus: String
    let isEphemeral: Bool

    nonisolated init(
        hostname: String,
        firstSeen: Date,
        lastSeen: Date,
        recurrenceCount: Int,
        statusChangeCount: Int,
        lastKnownStatus: String,
        isEphemeral: Bool
    ) {
        id = hostname.lowercased()
        self.hostname = hostname
        self.firstSeen = firstSeen
        self.lastSeen = lastSeen
        self.recurrenceCount = recurrenceCount
        self.statusChangeCount = statusChangeCount
        self.lastKnownStatus = lastKnownStatus
        self.isEphemeral = isEphemeral
    }
}

struct IntelligenceRiskSignal: Identifiable, Codable, Equatable, Sendable {
    let id: String
    let title: String
    let detail: String
    let severity: ChangeSeverity
    let firstObserved: Date?
    let lastObserved: Date?

    nonisolated init(
        id: String,
        title: String,
        detail: String,
        severity: ChangeSeverity,
        firstObserved: Date? = nil,
        lastObserved: Date? = nil
    ) {
        self.id = id
        self.title = title
        self.detail = detail
        self.severity = severity
        self.firstObserved = firstObserved
        self.lastObserved = lastObserved
    }
}

enum IntelligenceTimelineEventCategory: String, Codable, Sendable {
    case ownership
    case dns
    case hosting
    case subdomain
    case classification
    case risk
}

struct IntelligenceTimelineEvent: Identifiable, Codable, Equatable, Sendable {
    let id: UUID
    let date: Date
    let category: IntelligenceTimelineEventCategory
    let title: String
    let detail: String
    let severity: ChangeSeverity

    nonisolated init(
        id: UUID = UUID(),
        date: Date,
        category: IntelligenceTimelineEventCategory,
        title: String,
        detail: String,
        severity: ChangeSeverity
    ) {
        self.id = id
        self.date = date
        self.category = category
        self.title = title
        self.detail = detail
        self.severity = severity
    }
}

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

enum DomainReputationStatus: String, Codable, Sendable {
    case clean
    case listed
    case unknown

    var title: String {
        switch self {
        case .clean:
            return "Clean"
        case .listed:
            return "Listed"
        case .unknown:
            return "Unknown"
        }
    }
}

struct DomainReputationResult: Codable, Equatable, Sendable {
    let status: DomainReputationStatus
    let listedSources: [String]
    let checkedAt: 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, Codable {
    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, Codable {
    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"
        }
    }
}

/// A named watchlist filter preset (tag, filter, sort) the user can save and
/// reapply. Stored locally in UserDefaults; not included in backup/restore.
struct WatchlistSavedView: Codable, Identifiable, Equatable {
    let id: UUID
    var name: String
    var tag: String?
    var filter: WatchlistFilterOption
    var sort: WatchlistSortOption

    init(
        id: UUID = UUID(),
        name: String,
        tag: String?,
        filter: WatchlistFilterOption,
        sort: WatchlistSortOption
    ) {
        self.id = id
        self.name = name
        self.tag = tag
        self.filter = filter
        self.sort = sort
    }
}

enum PortfolioFilterOption: String, CaseIterable, Identifiable {
    case all
    case healthy
    case warning
    case critical
    case changed
    case expiring
    case unreachable

    var id: String { rawValue }

    var title: String {
        switch self {
        case .all:
            return "All"
        case .healthy:
            return "Healthy"
        case .warning:
            return "Warning"
        case .critical:
            return "Critical"
        case .changed:
            return "Changed"
        case .expiring:
            return "Expiring"
        case .unreachable:
            return "Unreachable"
        }
    }
}

extension DomainHealth {
    static func classify(
        certificateExpiryState: CertificateWarningLevel,
        isReachable: Bool,
        recentMonitoringFailureCount: Int,
        hasRecentDNSChange: Bool,
        instabilityScore: Int,
        hasRecentCriticalChange: Bool,
        hasInvalidTLS: Bool
    ) -> DomainHealth {
        if !isReachable
            || hasInvalidTLS
            || certificateExpiryState == .critical
            || recentMonitoringFailureCount >= 2
            || instabilityScore >= 70
            || hasRecentCriticalChange {
            return .critical
        }

        if certificateExpiryState == .warning
            || recentMonitoringFailureCount == 1
            || hasRecentDNSChange
            || instabilityScore >= 35 {
            return .warning
        }

        return .healthy
    }

    static func instabilityScore(
        recentChangeCount: Int,
        recentFailureCount: Int,
        pendingAlertCount: Int,
        hasRecentDNSChange: Bool
    ) -> Int {
        let rawScore = (recentChangeCount * 12)
            + (recentFailureCount * 24)
            + (pendingAlertCount * 8)
            + (hasRecentDNSChange ? 14 : 0)
        return min(rawScore, 100)
    }
}

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?
    var tags: [String]

    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,
        tags: [String] = []
    ) {
        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
        self.tags = tags
    }

    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)
        tags = try container.decodeIfPresent([String].self, forKey: .tags) ?? []
    }
}

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?
    /// Non-nil when the lookup failed and the previous snapshot was reused, so
    /// this run compared the old data against itself and cannot claim the
    /// domain is unchanged. Optional so already-persisted logs still decode.
    let unreachableReason: String?

    init(
        id: UUID = UUID(),
        domain: String,
        historyEntryID: UUID?,
        checkedAt: Date,
        didChange: Bool,
        summaryMessage: String,
        alertSeverity: MonitoringAlertSeverity?,
        certificateWarningLevel: CertificateWarningLevel,
        resultSource: LookupResultSource,
        errorMessage: String? = nil,
        unreachableReason: 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
        self.unreachableReason = unreachableReason
    }
}

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"
    }
}

enum EventSeverity: String, Codable, CaseIterable, Comparable, Identifiable, Sendable {
    case info
    case warning
    case critical

    var id: String { rawValue }

    static func < (lhs: EventSeverity, rhs: EventSeverity) -> Bool {
        lhs.rank < rhs.rank
    }

    var title: String {
        rawValue.capitalized
    }

    private var rank: Int {
        switch self {
        case .info:
            return 0
        case .warning:
            return 1
        case .critical:
            return 2
        }
    }

    init(monitoringSeverity: MonitoringAlertSeverity) {
        switch monitoringSeverity {
        case .info:
            self = .info
        case .warning:
            self = .warning
        case .critical:
            self = .critical
        }
    }
}

enum MonitoringEventType: String, Codable, CaseIterable, Identifiable, Sendable {
    case dnsChanged
    case certificateUpdated
    case certificateExpiring
    case redirectChanged
    case headersChanged
    case endpointUnreachable
    case monitoringFailure
    case changeDetected
    case test

    var id: String { rawValue }

    var title: String {
        switch self {
        case .dnsChanged:
            return "DNS Changed"
        case .certificateUpdated:
            return "Certificate Updated"
        case .certificateExpiring:
            return "Certificate Expiring"
        case .redirectChanged:
            return "Redirect Changed"
        case .headersChanged:
            return "Headers Changed"
        case .endpointUnreachable:
            return "Endpoint Unreachable"
        case .monitoringFailure:
            return "Monitoring Failure"
        case .changeDetected:
            return "Change Detected"
        case .test:
            return "Test Event"
        }
    }
}

struct MonitoringEvent: Codable, Identifiable, Equatable, Sendable {
    var id: UUID
    var type: MonitoringEventType
    var severity: EventSeverity
    var domain: String
    var timestamp: Date
    var summary: String
    var details: [String: String]

    init(
        id: UUID = UUID(),
        type: MonitoringEventType,
        severity: EventSeverity,
        domain: String,
        timestamp: Date = Date(),
        summary: String,
        details: [String: String] = [:]
    ) {
        self.id = id
        self.type = type
        self.severity = severity
        self.domain = domain
        self.timestamp = timestamp
        self.summary = summary
        self.details = details
    }
}

enum IntegrationType: String, Codable, CaseIterable, Identifiable, Sendable {
    case webhook
    case slack
    case email

    var id: String { rawValue }

    var title: String {
        rawValue.capitalized
    }
}

enum SMTPSecurityMode: String, Codable, CaseIterable, Identifiable, Sendable {
    case plain
    case directTLS

    var id: String { rawValue }

    var title: String {
        switch self {
        case .plain:
            return "Plain"
        case .directTLS:
            return "Direct TLS"
        }
    }
}

struct WebhookIntegrationConfiguration: Codable, Equatable, Sendable {
    var endpointDisplayHost: String
    var timeoutSeconds: Double
    var additionalHeaders: [String: String]
    var credentialReference: String?

    init(
        endpointDisplayHost: String = "",
        timeoutSeconds: Double = 15,
        additionalHeaders: [String: String] = [:],
        credentialReference: String? = nil
    ) {
        self.endpointDisplayHost = endpointDisplayHost
        self.timeoutSeconds = timeoutSeconds
        self.additionalHeaders = additionalHeaders
        self.credentialReference = credentialReference
    }
}

struct SlackIntegrationConfiguration: Codable, Equatable, Sendable {
    var destinationLabel: String
    var credentialReference: String?

    init(
        destinationLabel: String = "Slack",
        credentialReference: String? = nil
    ) {
        self.destinationLabel = destinationLabel
        self.credentialReference = credentialReference
    }
}

struct EmailIntegrationConfiguration: Codable, Equatable, Sendable {
    var smtpHost: String
    var port: Int
    var username: String
    var senderAddress: String
    var recipientAddresses: [String]
    var securityMode: SMTPSecurityMode
    var credentialReference: String?

    init(
        smtpHost: String = "",
        port: Int = 465,
        username: String = "",
        senderAddress: String = "",
        recipientAddresses: [String] = [],
        securityMode: SMTPSecurityMode = .directTLS,
        credentialReference: String? = nil
    ) {
        self.smtpHost = smtpHost
        self.port = port
        self.username = username
        self.senderAddress = senderAddress
        self.recipientAddresses = recipientAddresses
        self.securityMode = securityMode
        self.credentialReference = credentialReference
    }
}

enum IntegrationConfiguration: Codable, Equatable, Sendable {
    case webhook(WebhookIntegrationConfiguration)
    case slack(SlackIntegrationConfiguration)
    case email(EmailIntegrationConfiguration)

    private enum CodingKeys: String, CodingKey {
        case type
        case webhook
        case slack
        case email
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let type = try container.decode(IntegrationType.self, forKey: .type)
        switch type {
        case .webhook:
            self = .webhook(try container.decode(WebhookIntegrationConfiguration.self, forKey: .webhook))
        case .slack:
            self = .slack(try container.decode(SlackIntegrationConfiguration.self, forKey: .slack))
        case .email:
            self = .email(try container.decode(EmailIntegrationConfiguration.self, forKey: .email))
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        switch self {
        case .webhook(let configuration):
            try container.encode(IntegrationType.webhook, forKey: .type)
            try container.encode(configuration, forKey: .webhook)
        case .slack(let configuration):
            try container.encode(IntegrationType.slack, forKey: .type)
            try container.encode(configuration, forKey: .slack)
        case .email(let configuration):
            try container.encode(IntegrationType.email, forKey: .type)
            try container.encode(configuration, forKey: .email)
        }
    }

    var type: IntegrationType {
        switch self {
        case .webhook:
            return .webhook
        case .slack:
            return .slack
        case .email:
            return .email
        }
    }
}

struct IntegrationFilterSet: Codable, Equatable, Sendable {
    var minimumSeverity: EventSeverity
    var eventTypes: Set<MonitoringEventType>
    var domains: [String]

    init(
        minimumSeverity: EventSeverity = .warning,
        eventTypes: Set<MonitoringEventType> = Set(MonitoringEventType.allCases.filter { $0 != .test }),
        domains: [String] = []
    ) {
        self.minimumSeverity = minimumSeverity
        self.eventTypes = eventTypes
        self.domains = domains
    }

    func matches(_ event: MonitoringEvent) -> Bool {
        guard event.severity >= minimumSeverity else {
            return false
        }
        guard eventTypes.isEmpty || eventTypes.contains(event.type) else {
            return false
        }
        guard domains.isEmpty || domains.map({ $0.lowercased() }).contains(event.domain.lowercased()) else {
            return false
        }
        return true
    }
}

struct IntegrationTarget: Codable, Identifiable, Equatable, Sendable {
    var id: UUID
    var type: IntegrationType
    var name: String
    var isEnabled: Bool
    var configuration: IntegrationConfiguration
    var filters: IntegrationFilterSet

    init(
        id: UUID = UUID(),
        type: IntegrationType,
        name: String,
        isEnabled: Bool = true,
        configuration: IntegrationConfiguration,
        filters: IntegrationFilterSet = IntegrationFilterSet()
    ) {
        self.id = id
        self.type = type
        self.name = name
        self.isEnabled = isEnabled
        self.configuration = configuration
        self.filters = filters
    }
}

enum DeliveryStatus: String, Codable, CaseIterable, Identifiable, Sendable {
    case pending
    case retrying
    case delivered
    case failed
    case expired
    case skipped

    var id: String { rawValue }

    var title: String {
        rawValue.capitalized
    }
}

struct DeliveryRecord: Codable, Identifiable, Equatable, Sendable {
    var id: UUID
    var integrationID: UUID
    var eventID: UUID
    var timestamp: Date
    var status: DeliveryStatus
    var destination: String
    var summary: String
    var failureReason: String?
    var attemptCount: Int

    init(
        id: UUID = UUID(),
        integrationID: UUID,
        eventID: UUID,
        timestamp: Date = Date(),
        status: DeliveryStatus,
        destination: String,
        summary: String,
        failureReason: String? = nil,
        attemptCount: Int = 0
    ) {
        self.id = id
        self.integrationID = integrationID
        self.eventID = eventID
        self.timestamp = timestamp
        self.status = status
        self.destination = destination
        self.summary = summary
        self.failureReason = failureReason
        self.attemptCount = attemptCount
    }
}

struct QueuedDelivery: Codable, Identifiable, Equatable, Sendable {
    var id: UUID
    var integrationID: UUID
    var event: MonitoringEvent
    var createdAt: Date
    var attemptCount: Int
    var nextAttemptAt: Date
    var lastError: String?
    var expiresAt: Date

    init(
        id: UUID = UUID(),
        integrationID: UUID,
        event: MonitoringEvent,
        createdAt: Date = Date(),
        attemptCount: Int = 0,
        nextAttemptAt: Date = Date(),
        lastError: String? = nil,
        expiresAt: Date = Date().addingTimeInterval(3 * 24 * 60 * 60)
    ) {
        self.id = id
        self.integrationID = integrationID
        self.event = event
        self.createdAt = createdAt
        self.attemptCount = attemptCount
        self.nextAttemptAt = nextAttemptAt
        self.lastError = lastError
        self.expiresAt = expiresAt
    }
}

// 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 inferredProvider: InferredProviderFingerprint?
    var priorProviders: [String]
    var domainClassification: DomainClassificationSummary?
    var ownershipTransitions: [OwnershipTransitionEvent]
    var hostingTransitions: [HostingTransitionEvent]
    var subdomainHistory: [SubdomainHistoryEntry]
    var riskSignals: [IntelligenceRiskSignal]
    var intelligenceTimeline: [IntelligenceTimelineEvent]
    var ptrRecord: String?
    var redirectChain: [RedirectHop]
    var subdomains: [DiscoveredSubdomain]
    var extendedSubdomains: [DiscoveredSubdomain]
    var dnsHistory: [DNSHistoryEvent]
    var domainPricing: DomainPricingInsight?
    var reputation: DomainReputationResult?
    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 reputationError: 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] = [],
         inferredProvider: InferredProviderFingerprint? = nil, priorProviders: [String] = [],
         domainClassification: DomainClassificationSummary? = nil,
         ownershipTransitions: [OwnershipTransitionEvent] = [],
         hostingTransitions: [HostingTransitionEvent] = [],
         subdomainHistory: [SubdomainHistoryEntry] = [],
         riskSignals: [IntelligenceRiskSignal] = [],
         intelligenceTimeline: [IntelligenceTimelineEvent] = [],
         ptrRecord: String? = nil, redirectChain: [RedirectHop] = [], subdomains: [DiscoveredSubdomain] = [],
         extendedSubdomains: [DiscoveredSubdomain] = [], dnsHistory: [DNSHistoryEvent] = [],
         domainPricing: DomainPricingInsight? = nil,
         reputation: DomainReputationResult? = 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, reputationError: 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.inferredProvider = inferredProvider
        self.priorProviders = priorProviders
        self.domainClassification = domainClassification
        self.ownershipTransitions = ownershipTransitions
        self.hostingTransitions = hostingTransitions
        self.subdomainHistory = subdomainHistory
        self.riskSignals = riskSignals
        self.intelligenceTimeline = intelligenceTimeline
        self.ptrRecord = ptrRecord
        self.redirectChain = redirectChain
        self.subdomains = subdomains
        self.extendedSubdomains = extendedSubdomains
        self.dnsHistory = dnsHistory
        self.domainPricing = domainPricing
        self.reputation = reputation
        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.reputationError = reputationError
        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) ?? []
        inferredProvider = try container.decodeIfPresent(InferredProviderFingerprint.self, forKey: .inferredProvider)
        priorProviders = try container.decodeIfPresent([String].self, forKey: .priorProviders) ?? []
        domainClassification = try container.decodeIfPresent(DomainClassificationSummary.self, forKey: .domainClassification)
        ownershipTransitions = try container.decodeIfPresent([OwnershipTransitionEvent].self, forKey: .ownershipTransitions) ?? []
        hostingTransitions = try container.decodeIfPresent([HostingTransitionEvent].self, forKey: .hostingTransitions) ?? []
        subdomainHistory = try container.decodeIfPresent([SubdomainHistoryEntry].self, forKey: .subdomainHistory) ?? []
        riskSignals = try container.decodeIfPresent([IntelligenceRiskSignal].self, forKey: .riskSignals) ?? []
        intelligenceTimeline = try container.decodeIfPresent([IntelligenceTimelineEvent].self, forKey: .intelligenceTimeline) ?? []
        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)
        reputation = try container.decodeIfPresent(DomainReputationResult.self, forKey: .reputation)
        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)
        reputationError = try container.decodeIfPresent(String.self, forKey: .reputationError)
        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
    }
}