igniscope 0.1.0

Deterministic CLI analyzer for Ignition project exports and gateway backups.
Documentation
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
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::io::Read;
use std::path::Path;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use zip::ZipArchive;

use crate::error::AppError;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchiveKind {
    ProjectExport,
    GatewayBackup,
    Unknown,
}

impl ArchiveKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ProjectExport => "project_export",
            Self::GatewayBackup => "gateway_backup",
            Self::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectSelection {
    Single { root: String },
    Multiple { roots: Vec<String> },
    None,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArchiveInspection {
    pub archive_kind: ArchiveKind,
    pub project_selection: ProjectSelection,
    pub detected_project_roots: Vec<String>,
    pub selected_project_roots: Vec<String>,
}

/// Metadata extracted from a `project.json` document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ProjectMetadata {
    pub project_root: String,
    pub title: String,
    pub description: Option<String>,
    pub parent: Option<String>,
    pub enabled: bool,
    pub inheritable: bool,
}

/// A discovered project resource and its normalized metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct Resource {
    pub section: String,
    pub type_key: String,
    pub path: String,
    pub resource_json_path: String,
    pub binary_only: bool,
    pub attributes: BTreeMap<String, Value>,
    pub files: Vec<ResourceFile>,
}

/// A single file that belongs to a discovered resource.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResourceFile {
    pub file_kind: String,
    pub file_zip_path: String,
}

/// Resource inventory for a single selected project root.
#[derive(Debug, Clone, PartialEq)]
pub struct ProjectResourceInventory {
    pub project_root: String,
    pub resources: Vec<Resource>,
}

/// Aggregated deterministic counters for one project resource inventory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ProjectCounts {
    pub resources_total: usize,
    pub files_total: usize,
    pub binary_only_resources: usize,
    pub resources_by_section: BTreeMap<String, usize>,
    pub resources_by_type: BTreeMap<String, usize>,
    pub files_by_kind: BTreeMap<String, usize>,
}

/// Coverage values derived from classified resources in one project.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CoverageMetrics {
    pub unknown_resources: usize,
    pub unknown_ratio: f64,
}

/// Classification result for a single resource path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Classification {
    section: &'static str,
    type_key: &'static str,
}

/// Top-level in-memory analytics bundle that mirrors `analytics.json`.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AnalyticsBundle {
    pub schema_version: String,
    pub generated_at: String,
    pub input: AnalyticsInput,
    pub summary: AnalyticsSummary,
    pub projects: Vec<ProjectAnalytics>,
    pub issues: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gateway_meta: Option<Value>,
}

/// Input metadata for the analytics schema.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct AnalyticsInput {
    pub archive_path: String,
    pub archive_kind: String,
    pub detected_project_roots: Vec<String>,
    pub selected_project_roots: Vec<String>,
}

/// Per-project analytics entry in the unified schema.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ProjectAnalytics {
    pub project_root: String,
    pub project: ProjectMetadata,
    pub counts: ProjectCounts,
    pub coverage: CoverageMetrics,
    pub issues: Vec<String>,
}

/// Aggregate summary across all project entries.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AnalyticsSummary {
    pub projects_total: usize,
    pub resources_total: usize,
    pub files_total: usize,
    pub binary_only_resources: usize,
    pub resources_by_section: BTreeMap<String, usize>,
    pub resources_by_type: BTreeMap<String, usize>,
    pub files_by_kind: BTreeMap<String, usize>,
    pub unknown_resources: usize,
    pub unknown_ratio: f64,
}

#[derive(Debug, Deserialize)]
struct RawProjectFile {
    title: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    parent: Option<String>,
    #[serde(default = "default_enabled")]
    enabled: bool,
    #[serde(default)]
    inheritable: bool,
}

/// Default for missing `enabled` keys in `project.json`.
/// # TODO is there a better way for constants + serde?
const fn default_enabled() -> bool {
    true
}

const SECTION_PERSPECTIVE: &str = "Perspective";
const SECTION_SCRIPTING: &str = "Scripting";
const SECTION_NAMED_QUERIES: &str = "Named Queries";
const SECTION_SFC: &str = "Sequential Function Charts (SFC)";
const SECTION_EVENT_STREAMS: &str = "Event Streams";
const SECTION_REPORTS: &str = "Reports";
const SECTION_ALARM_PIPELINES: &str = "Alarm Notification Pipelines";
const SECTION_PROPERTIES: &str = "Properties";
const SECTION_OTHER: &str = "Other";

const TYPE_PERSPECTIVE_VIEW: &str = "perspective.view";
const TYPE_PERSPECTIVE_PAGE_CONFIG: &str = "perspective.page_config";
const TYPE_PERSPECTIVE_STYLE_CLASS: &str = "perspective.style_class";
const TYPE_PERSPECTIVE_STYLESHEET: &str = "perspective.stylesheet";
const TYPE_PERSPECTIVE_MESSAGE_HANDLER: &str = "perspective.message_handler";
const TYPE_PERSPECTIVE_FORM_SUBMISSION_HANDLER: &str = "perspective.form_submission_handler";
const TYPE_PERSPECTIVE_KEY_EVENT: &str = "perspective.key_event";
const TYPE_PERSPECTIVE_STARTUP: &str = "perspective.startup";
const TYPE_PERSPECTIVE_SHUTDOWN: &str = "perspective.shutdown";
const TYPE_PERSPECTIVE_ACCELEROMETER: &str = "perspective.accelerometer";
const TYPE_PERSPECTIVE_BARCODE: &str = "perspective.barcode";
const TYPE_PERSPECTIVE_BLUETOOTH: &str = "perspective.bluetooth";
const TYPE_PERSPECTIVE_AUTH_CHALLENGE: &str = "perspective.auth_challenge";
const TYPE_PERSPECTIVE_NFC_SCAN: &str = "perspective.nfc_scan";
const TYPE_PERSPECTIVE_PAGE_STARTUP: &str = "perspective.page_startup";
const TYPE_PERSPECTIVE_SESSION_PROPS: &str = "perspective.session_props";
const TYPE_SCRIPT_PYTHON: &str = "script.python";
const TYPE_SCRIPT_GATEWAY_EVENT: &str = "script.gateway_event";
const TYPE_NAMED_QUERY: &str = "named_query";
const TYPE_SFC: &str = "sfc";
const TYPE_EVENT_STREAM: &str = "event_stream";
const TYPE_REPORT: &str = "report";
const TYPE_ALARM_PIPELINE: &str = "alarm_pipeline";
const TYPE_PROJECT_PROPERTIES: &str = "project_properties";
const TYPE_UNKNOWN: &str = "unknown";

/// Inspects an archive and returns its kind plus selected project.
pub fn inspect_archive(archive_path: &Path) -> Result<ArchiveInspection, AppError> {
    let entries = list_archive_entries(archive_path)?;
    inspect_entries(archive_path, &entries)
}

/// Lists archive entries in deterministic (sorted, deduplicated) order.
pub fn list_archive_entries(archive_path: &Path) -> Result<Vec<String>, AppError> {
    let file = File::open(archive_path).map_err(|err| {
        AppError::archive_read(archive_path, format!("could not open file: {err}"))
    })?;

    let mut archive = ZipArchive::new(file).map_err(|err| {
        AppError::archive_read(archive_path, format!("not a valid zip archive: {err}"))
    })?;

    let mut entries = Vec::with_capacity(archive.len());
    for index in 0..archive.len() {
        let zip_entry = archive.by_index(index).map_err(|err| {
            AppError::archive_read(
                archive_path,
                format!("could not read zip entry at index {index}: {err}"),
            )
        })?;

        let normalized = normalize_zip_entry_name(zip_entry.name());
        if !normalized.is_empty() {
            entries.push(normalized);
        }
    }

    entries.sort();
    entries.dedup();
    Ok(entries)
}

/// Parses `project.json` for each selected root, preserving root order.
pub fn parse_project_metadata(
    archive_path: &Path,
    selected_project_roots: &[String],
) -> Result<Vec<ProjectMetadata>, AppError> {
    let file = File::open(archive_path).map_err(|err| {
        AppError::archive_read(archive_path, format!("could not open file: {err}"))
    })?;

    let mut archive = ZipArchive::new(file).map_err(|err| {
        AppError::archive_read(archive_path, format!("not a valid zip archive: {err}"))
    })?;

    let mut projects = Vec::with_capacity(selected_project_roots.len());
    for project_root in selected_project_roots {
        let project_json_path = project_json_member_path(project_root);
        let mut member = archive.by_name(&project_json_path).map_err(|err| {
            AppError::archive_read(
                archive_path,
                format!("missing expected `{project_json_path}`: {err}"),
            )
        })?;

        let mut bytes = Vec::new();
        member.read_to_end(&mut bytes).map_err(|err| {
            AppError::archive_read(
                archive_path,
                format!("could not read `{project_json_path}`: {err}"),
            )
        })?;

        let project = parse_project_json_bytes(archive_path, &project_json_path, &bytes)?;
        projects.push(project.with_root(project_root.clone()));
    }

    Ok(projects)
}

/// Discovers and validates resources for all selected project roots.
///
/// This validates:
/// - a resource exists only when `<folder>/resource.json` exists
/// - `resource.json.files` must be a string array
/// - every declared file must exist in the archive
/// - undeclared `data.bin` is appended once at the end when present
pub fn discover_resources_for_roots(
    archive_path: &Path,
    selected_project_roots: &[String],
) -> Result<Vec<ProjectResourceInventory>, AppError> {
    let entries = list_archive_entries(archive_path)?;
    let entry_set: BTreeSet<String> = entries.iter().cloned().collect();

    let file = File::open(archive_path).map_err(|err| {
        AppError::archive_read(archive_path, format!("could not open file: {err}"))
    })?;

    let mut archive = ZipArchive::new(file).map_err(|err| {
        AppError::archive_read(archive_path, format!("not a valid zip archive: {err}"))
    })?;

    let mut inventories = Vec::with_capacity(selected_project_roots.len());
    for project_root in selected_project_roots {
        let resources = discover_resources_for_root_in_archive(
            &mut archive,
            archive_path,
            project_root,
            &entries,
            &entry_set,
        )?;

        inventories.push(ProjectResourceInventory {
            project_root: project_root.clone(),
            resources,
        });
    }

    Ok(inventories)
}

/// Discovers and validates resources for a single project root.
pub fn discover_resources_for_root(
    archive_path: &Path,
    project_root: &str,
) -> Result<Vec<Resource>, AppError> {
    let inventories = discover_resources_for_roots(archive_path, &[project_root.to_string()])?;
    Ok(inventories
        .into_iter()
        .next()
        .map(|inventory| inventory.resources)
        .unwrap_or_default())
}

/// Aggregates deterministic resource/file counters for a project.
pub fn compute_project_counts(resources: &[Resource]) -> ProjectCounts {
    let mut resources_by_section = BTreeMap::new();
    let mut resources_by_type = BTreeMap::new();
    let mut files_by_kind = BTreeMap::new();
    let mut files_total = 0usize;
    let mut binary_only_resources = 0usize;

    for resource in resources {
        *resources_by_section
            .entry(resource.section.clone())
            .or_insert(0usize) += 1;
        *resources_by_type
            .entry(resource.type_key.clone())
            .or_insert(0usize) += 1;

        if resource.binary_only {
            binary_only_resources += 1;
        }

        files_total += resource.files.len();
        for file in &resource.files {
            *files_by_kind
                .entry(file.file_kind.clone())
                .or_insert(0usize) += 1;
        }
    }

    ProjectCounts {
        resources_total: resources.len(),
        files_total,
        binary_only_resources,
        resources_by_section,
        resources_by_type,
        files_by_kind,
    }
}

/// Computes unknown-resource coverage metrics for one project.
pub fn compute_coverage(resources: &[Resource]) -> CoverageMetrics {
    let unknown_resources = resources
        .iter()
        .filter(|resource| resource.type_key == TYPE_UNKNOWN)
        .count();
    let total = resources.len();
    let unknown_ratio = if total == 0 {
        0.0
    } else {
        unknown_resources as f64 / total as f64
    };

    CoverageMetrics {
        unknown_resources,
        unknown_ratio,
    }
}

/// Builds a schema-aligned analytics bundle for one inspected archive.
pub fn build_analytics_bundle(
    archive_path: &Path,
    generated_at: impl Into<String>,
    inspection: &ArchiveInspection,
    project_metadata: &[ProjectMetadata],
    resource_inventories: &[ProjectResourceInventory],
) -> Result<AnalyticsBundle, AppError> {
    let mut metadata_by_root = BTreeMap::new();
    for meta in project_metadata {
        if metadata_by_root
            .insert(meta.project_root.clone(), meta.clone())
            .is_some()
        {
            return Err(AppError::internal(format!(
                "duplicate project metadata entry for root `{}`",
                meta.project_root
            )));
        }
    }

    let mut resources_by_root = BTreeMap::new();
    for inventory in resource_inventories {
        if resources_by_root
            .insert(inventory.project_root.clone(), inventory.resources.clone())
            .is_some()
        {
            return Err(AppError::internal(format!(
                "duplicate resource inventory entry for root `{}`",
                inventory.project_root
            )));
        }
    }

    let mut sorted_selected_roots = inspection.selected_project_roots.clone();
    sorted_selected_roots.sort();

    let mut projects = Vec::with_capacity(sorted_selected_roots.len());
    for project_root in &sorted_selected_roots {
        let project = metadata_by_root.remove(project_root).ok_or_else(|| {
            AppError::internal(format!(
                "missing project metadata for root `{project_root}`"
            ))
        })?;
        let resources = resources_by_root.remove(project_root).ok_or_else(|| {
            AppError::internal(format!(
                "missing resource inventory for root `{project_root}`"
            ))
        })?;

        projects.push(ProjectAnalytics {
            project_root: project_root.clone(),
            counts: compute_project_counts(&resources),
            coverage: compute_coverage(&resources),
            project,
            issues: Vec::new(),
        });
    }

    if !metadata_by_root.is_empty() {
        let roots = metadata_by_root
            .keys()
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        return Err(AppError::internal(format!(
            "project metadata roots not selected by inspection: {roots}"
        )));
    }
    if !resources_by_root.is_empty() {
        let roots = resources_by_root
            .keys()
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        return Err(AppError::internal(format!(
            "resource inventory roots not selected by inspection: {roots}"
        )));
    }

    let summary = aggregate_summary(&projects);

    Ok(AnalyticsBundle {
        schema_version: "0.1.0".to_string(),
        generated_at: generated_at.into(),
        input: AnalyticsInput {
            archive_path: archive_path.display().to_string(),
            archive_kind: inspection.archive_kind.as_str().to_string(),
            detected_project_roots: inspection.detected_project_roots.clone(),
            selected_project_roots: sorted_selected_roots,
        },
        summary,
        projects,
        issues: Vec::new(),
        gateway_meta: None,
    })
}

/// Aggregates summary counters and coverage across all project analytics entries.
pub fn aggregate_summary(projects: &[ProjectAnalytics]) -> AnalyticsSummary {
    let mut resources_total = 0usize;
    let mut files_total = 0usize;
    let mut binary_only_resources = 0usize;
    let mut unknown_resources = 0usize;

    let mut resources_by_section = BTreeMap::new();
    let mut resources_by_type = BTreeMap::new();
    let mut files_by_kind = BTreeMap::new();

    for project in projects {
        resources_total += project.counts.resources_total;
        files_total += project.counts.files_total;
        binary_only_resources += project.counts.binary_only_resources;
        unknown_resources += project.coverage.unknown_resources;

        for (key, value) in &project.counts.resources_by_section {
            *resources_by_section.entry(key.clone()).or_insert(0usize) += value;
        }
        for (key, value) in &project.counts.resources_by_type {
            *resources_by_type.entry(key.clone()).or_insert(0usize) += value;
        }
        for (key, value) in &project.counts.files_by_kind {
            *files_by_kind.entry(key.clone()).or_insert(0usize) += value;
        }
    }

    let unknown_ratio = if resources_total == 0 {
        0.0
    } else {
        unknown_resources as f64 / resources_total as f64
    };

    AnalyticsSummary {
        projects_total: projects.len(),
        resources_total,
        files_total,
        binary_only_resources,
        resources_by_section,
        resources_by_type,
        files_by_kind,
        unknown_resources,
        unknown_ratio,
    }
}

/// Classifies a normalized resource path into section and `type_key`.
fn classify_resource_path(path: &str) -> Classification {
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/views") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_VIEW,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/page-config") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_PAGE_CONFIG,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/style-classes") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_STYLE_CLASS,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/stylesheet") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_STYLESHEET,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/message") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_MESSAGE_HANDLER,
        };
    }
    if is_prefix_or_exact(
        path,
        "com.inductiveautomation.perspective/form-submission-handler",
    ) {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_FORM_SUBMISSION_HANDLER,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/key-event") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_KEY_EVENT,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/startup") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_STARTUP,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/shutdown") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_SHUTDOWN,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/accelerometer") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_ACCELEROMETER,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/barcode") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_BARCODE,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/bluetooth") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_BLUETOOTH,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/auth-challenge") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_AUTH_CHALLENGE,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/nfc-scan") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_NFC_SCAN,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/page-startup") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_PAGE_STARTUP,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.perspective/session-props") {
        return Classification {
            section: SECTION_PERSPECTIVE,
            type_key: TYPE_PERSPECTIVE_SESSION_PROPS,
        };
    }
    if is_prefix_or_exact(path, "ignition/script-python") {
        return Classification {
            section: SECTION_SCRIPTING,
            type_key: TYPE_SCRIPT_PYTHON,
        };
    }
    if is_prefix_or_exact(path, "ignition/startup")
        || is_prefix_or_exact(path, "ignition/shutdown")
        || is_prefix_or_exact(path, "ignition/update")
        || is_prefix_or_exact(path, "ignition/timer")
        || is_prefix_or_exact(path, "ignition/tag-change")
        || is_prefix_or_exact(path, "ignition/scheduled")
        || is_prefix_or_exact(path, "ignition/event-scripts")
    {
        return Classification {
            section: SECTION_SCRIPTING,
            type_key: TYPE_SCRIPT_GATEWAY_EVENT,
        };
    }
    if is_prefix_or_exact(path, "ignition/named-query") {
        return Classification {
            section: SECTION_NAMED_QUERIES,
            type_key: TYPE_NAMED_QUERY,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.sfc") {
        return Classification {
            section: SECTION_SFC,
            type_key: TYPE_SFC,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.eventstream") {
        return Classification {
            section: SECTION_EVENT_STREAMS,
            type_key: TYPE_EVENT_STREAM,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.reporting") {
        return Classification {
            section: SECTION_REPORTS,
            type_key: TYPE_REPORT,
        };
    }
    if is_prefix_or_exact(path, "com.inductiveautomation.alarm-notification") {
        return Classification {
            section: SECTION_ALARM_PIPELINES,
            type_key: TYPE_ALARM_PIPELINE,
        };
    }
    if is_prefix_or_exact(path, "ignition/global-props")
        || is_prefix_or_exact(path, "ignition/designer-properties")
    {
        return Classification {
            section: SECTION_PROPERTIES,
            type_key: TYPE_PROJECT_PROPERTIES,
        };
    }

    Classification {
        section: SECTION_OTHER,
        type_key: TYPE_UNKNOWN,
    }
}

/// Discovers and validates root-scoped resources from an opened archive.
fn discover_resources_for_root_in_archive(
    archive: &mut ZipArchive<File>,
    archive_path: &Path,
    project_root: &str,
    entries: &[String],
    entry_set: &BTreeSet<String>,
) -> Result<Vec<Resource>, AppError> {
    let mut resource_json_paths = Vec::new();
    for entry in entries {
        if is_resource_json_for_root(entry, project_root) {
            resource_json_paths.push(entry.clone());
        }
    }

    let mut resources = Vec::with_capacity(resource_json_paths.len());
    for resource_json_path in resource_json_paths {
        let mut member = archive.by_name(&resource_json_path).map_err(|err| {
            AppError::archive_read(
                archive_path,
                format!("missing expected `{resource_json_path}`: {err}"),
            )
        })?;

        let mut bytes = Vec::new();
        member.read_to_end(&mut bytes).map_err(|err| {
            AppError::archive_read(
                archive_path,
                format!("could not read `{resource_json_path}`: {err}"),
            )
        })?;

        let resource = parse_resource(archive_path, &resource_json_path, &bytes)?;
        let files = build_resource_files(
            archive_path,
            &resource_json_path,
            &resource.files,
            entry_set,
        )?;
        let resource_path = resource_path_for_project_root(&resource_json_path, project_root);
        let classification = classify_resource_path(&resource_path);
        // println!("resource_path: {:#?} classification={:#?} files={:#?}", resource_path, classification, files);

        resources.push(Resource {
            section: classification.section.to_string(),
            type_key: classification.type_key.to_string(),
            path: resource_path,
            resource_json_path,
            binary_only: is_binary_only_resource(&files),
            attributes: resource.attributes,
            files,
        });
    }

    resources.sort_by(|left, right| {
        (&left.section, &left.path, &left.resource_json_path).cmp(&(
            &right.section,
            &right.path,
            &right.resource_json_path,
        ))
    });

    Ok(resources)
}

/// Parses `project.json` into project metadata fields.
fn parse_project_json_bytes(
    archive_path: &Path,
    project_json_path: &str,
    bytes: &[u8],
) -> Result<RawProjectParsed, AppError> {
    let parsed: RawProjectFile = serde_json::from_slice(bytes).map_err(|err| {
        AppError::json_parse(
            archive_path,
            project_json_path,
            format!("invalid JSON payload: {err}"),
        )
    })?;

    Ok(RawProjectParsed {
        title: parsed.title,
        description: parsed.description,
        parent: parsed.parent,
        enabled: parsed.enabled,
        inheritable: parsed.inheritable,
    })
}

/// Builds the path leading to a project's `project.json` file.
/// TODO remove later
fn project_json_member_path(project_root: &str) -> String {
    if project_root.is_empty() {
        "project.json".to_string()
    } else {
        format!("{project_root}project.json")
    }
}

/// Parses `resource.json` and validates shape.
fn parse_resource(
    archive_path: &Path,
    resource_json_path: &str,
    bytes: &[u8],
) -> Result<RawResource, AppError> {
    let value: Value = serde_json::from_slice(bytes).map_err(|err| {
        AppError::json_parse(
            archive_path,
            resource_json_path,
            format!("invalid JSON payload: {err}"),
        )
    })?;

    let object = value.as_object().ok_or_else(|| {
        AppError::json_parse(
            archive_path,
            resource_json_path,
            "expected JSON object at resource root",
        )
    })?;

    let files_value = object.get("files").ok_or_else(|| {
        AppError::resource_integrity(format!(
            "Missing required `files` key in `{resource_json_path}` of `{}`",
            archive_path.display()
        ))
    })?;

    let files_array = files_value.as_array().ok_or_else(|| {
        AppError::resource_integrity(format!(
            "Expected `files` array in `{resource_json_path}` of `{}`",
            archive_path.display()
        ))
    })?;

    let mut files = Vec::with_capacity(files_array.len());
    for (index, entry) in files_array.iter().enumerate() {
        let file_name = entry.as_str().ok_or_else(|| {
            AppError::resource_integrity(format!(
                "Expected string at `files[{index}]` in `{resource_json_path}` of `{}`",
                archive_path.display()
            ))
        })?;

        if file_name.is_empty() {
            return Err(AppError::resource_integrity(format!(
                "Found empty file name at `files[{index}]` in `{resource_json_path}` of `{}`",
                archive_path.display()
            )));
        }

        files.push(file_name.to_string());
    }

    let mut attributes = BTreeMap::new();
    for (key, value) in object {
        if key != "files" {
            attributes.insert(key.clone(), value.clone());
        }
    }

    Ok(RawResource { files, attributes })
}

/// Builds a deterministically ordered file list for a resource.
fn build_resource_files(
    archive_path: &Path,
    resource_json_path: &str,
    resource_files: &[String],
    entry_set: &BTreeSet<String>,
) -> Result<Vec<ResourceFile>, AppError> {
    let resource_folder = resource_folder_path(resource_json_path).ok_or_else(|| {
        AppError::internal(format!(
            "invalid resource json path without suffix: {resource_json_path}"
        ))
    })?;

    let mut files = Vec::with_capacity(resource_files.len() + 2);
    files.push(ResourceFile {
        file_kind: "resource.json".to_string(),
        file_zip_path: resource_json_path.to_string(),
    });

    let mut has_data_bin_declared = false;
    for declared in resource_files {
        let file_zip_path = format!("{resource_folder}{declared}");
        if !entry_set.contains(&file_zip_path) {
            return Err(AppError::resource_integrity(format!(
                "Declared file `{declared}` is missing for `{resource_json_path}` in `{}`",
                archive_path.display()
            )));
        }

        if declared == "data.bin" {
            has_data_bin_declared = true;
        }

        files.push(ResourceFile {
            file_kind: file_kind_from_declared_name(declared),
            file_zip_path,
        });
    }

    let data_bin_path = format!("{resource_folder}data.bin");
    if !has_data_bin_declared && entry_set.contains(&data_bin_path) {
        files.push(ResourceFile {
            file_kind: "data.bin".to_string(),
            file_zip_path: data_bin_path,
        });
    }

    Ok(files)
}

/// Determines whether an entry path is a `resource.json` under a project root.
fn is_resource_json_for_root(entry: &str, project_root: &str) -> bool {
    if !entry.ends_with("/resource.json") {
        return false;
    }

    if project_root.is_empty() {
        return true;
    }

    entry.starts_with(project_root)
}

/// Returns the normalized resource path relative to a project root.
fn resource_path_for_project_root(resource_json_path: &str, project_root: &str) -> String {
    let folder = resource_folder_path(resource_json_path)
        .unwrap_or(resource_json_path)
        .trim_end_matches('/')
        .to_string();

    if project_root.is_empty() {
        return folder;
    }

    folder
        .strip_prefix(project_root)
        .unwrap_or(&folder)
        .to_string()
}

/// Returns the folder prefix for a `.../resource.json` path.
fn resource_folder_path(resource_json_path: &str) -> Option<&str> {
    resource_json_path.strip_suffix("resource.json")
}

/// Returns true when `path` equals `prefix` or starts with `prefix/`.
fn is_prefix_or_exact(path: &str, prefix: &str) -> bool {
    if path == prefix {
        return true;
    }

    match path.strip_prefix(prefix) {
        Some(rest) => rest.starts_with('/'),
        None => false,
    }
}

/// Maps a declared resource filename to a normalized file-kind label.
fn file_kind_from_declared_name(declared_file_name: &str) -> String {
    let file_name = declared_file_name
        .rsplit('/')
        .next()
        .unwrap_or(declared_file_name);

    if file_name.ends_with(".py") {
        "script".to_string()
    } else {
        file_name.to_string()
    }
}

/// Returns `true` when all payload files are binary-only (`data.bin`) entries.
fn is_binary_only_resource(files: &[ResourceFile]) -> bool {
    let mut payload_count = 0usize;
    for file in files {
        if file.file_kind == "resource.json" {
            continue;
        }

        payload_count += 1;
        if file.file_kind != "data.bin" {
            return false;
        }
    }

    payload_count > 0
}

/// Derives selected project entry names.
fn inspect_entries(archive_path: &Path, entries: &[String]) -> Result<ArchiveInspection, AppError> {
    let kind = detect_archive_kind(entries);
    let gateway_roots = detect_gateway_project_roots(entries);

    let (detected_project_roots, selected_project_roots) = match kind {
        ArchiveKind::ProjectExport => (vec![String::new()], vec![String::new()]),
        ArchiveKind::GatewayBackup => (gateway_roots.clone(), gateway_roots),
        ArchiveKind::Unknown => {
            return Err(AppError::project_root_detection(
                archive_path,
                "expected `project.json` at archive root or one/more `projects/<name>/project.json` roots",
            ));
        }
    };

    let project_selection = match selected_project_roots.len() {
        0 => ProjectSelection::None,
        1 => ProjectSelection::Single {
            root: selected_project_roots[0].clone(),
        },
        _ => ProjectSelection::Multiple {
            roots: selected_project_roots.clone(),
        },
    };

    Ok(ArchiveInspection {
        archive_kind: kind,
        project_selection,
        detected_project_roots,
        selected_project_roots,
    })
}

/// Detects archive kind from normalized entry names.
pub(crate) fn detect_archive_kind(entries: &[String]) -> ArchiveKind {
    let has_root_project = entries.iter().any(|entry| entry == "project.json");
    if has_root_project {
        return ArchiveKind::ProjectExport;
    }

    let gateway_roots = detect_gateway_project_roots(entries);
    if gateway_roots.is_empty() {
        ArchiveKind::Unknown
    } else {
        ArchiveKind::GatewayBackup
    }
}

/// Extracts gateway project roots from entry names.
pub(crate) fn detect_gateway_project_roots(entries: &[String]) -> Vec<String> {
    let mut roots = BTreeSet::new();

    for entry in entries {
        if let Some(project_name) = gateway_project_name(entry) {
            roots.insert(format!("projects/{project_name}/"));
        }
    }

    roots.into_iter().collect()
}

/// Returns a gateway project name when entry matches `projects/<name>/project.json`.
fn gateway_project_name(entry: &str) -> Option<&str> {
    let rest = entry.strip_prefix("projects/")?;
    let name = rest.strip_suffix("/project.json")?;
    if name.is_empty() || name.contains('/') {
        return None;
    }
    Some(name)
}

/// Normalizes entry names to forward slashes and strips leading separators.
fn normalize_zip_entry_name(name: &str) -> String {
    name.replace('\\', "/").trim_start_matches('/').to_string()
}

#[derive(Debug)]
struct RawProjectParsed {
    title: String,
    description: Option<String>,
    parent: Option<String>,
    enabled: bool,
    inheritable: bool,
}

impl RawProjectParsed {
    /// Attaches a project root to parsed `project.json` fields.
    fn with_root(self, project_root: String) -> ProjectMetadata {
        ProjectMetadata {
            project_root,
            title: self.title,
            description: self.description,
            parent: self.parent,
            enabled: self.enabled,
            inheritable: self.inheritable,
        }
    }
}

#[derive(Debug)]
struct RawResource {
    files: Vec<String>,
    attributes: BTreeMap<String, Value>,
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, BTreeSet};
    use std::path::{Path, PathBuf};

    use super::{
        ArchiveKind, ProjectSelection, Resource, ResourceFile, aggregate_summary,
        build_analytics_bundle, build_resource_files, classify_resource_path, compute_coverage,
        compute_project_counts, detect_archive_kind, detect_gateway_project_roots,
        discover_resources_for_root, discover_resources_for_roots, inspect_archive,
        is_binary_only_resource, parse_project_json_bytes, parse_project_metadata, parse_resource,
    };
    use crate::error::AppError;

    fn fixture_path(file_name: &str) -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests")
            .join("example-files")
            .join(file_name)
    }

    fn synthetic_resource(
        section: &str,
        type_key: &str,
        path: &str,
        binary_only: bool,
        file_kinds: &[&str],
    ) -> Resource {
        let files = file_kinds
            .iter()
            .enumerate()
            .map(|(index, kind)| ResourceFile {
                file_kind: (*kind).to_string(),
                file_zip_path: format!("{path}/file_{index}"),
            })
            .collect();

        Resource {
            section: section.to_string(),
            type_key: type_key.to_string(),
            path: path.to_string(),
            resource_json_path: format!("{path}/resource.json"),
            binary_only,
            attributes: BTreeMap::new(),
            files,
        }
    }

    #[test]
    fn archive_kind_detects_project_export_fixture() {
        let archive = inspect_archive(&fixture_path("Template_v8.3_example.zip"))
            .expect("fixture should be inspectable");
        assert_eq!(archive.archive_kind, ArchiveKind::ProjectExport);
    }

    #[test]
    fn archive_kind_detects_gateway_backup_fixture() {
        let archive = inspect_archive(&fixture_path("multi-project.gwbk"))
            .expect("fixture should be inspectable");
        assert_eq!(archive.archive_kind, ArchiveKind::GatewayBackup);
    }

    #[test]
    fn archive_kind_detects_unknown_fixture_as_error() {
        let err = inspect_archive(&fixture_path("data_center_industry_pack.1.1.0.zip"))
            .expect_err("wrapper archive should fail root detection");

        match err {
            AppError::ProjectRootDetection { .. } => {}
            other => panic!("expected project root detection error, got: {other:?}"),
        }
    }

    #[test]
    fn project_roots_for_project_export_is_root_only() {
        let archive = inspect_archive(&fixture_path("Template_v8.3_example.zip"))
            .expect("fixture should be inspectable");
        assert_eq!(archive.detected_project_roots, vec![String::new()]);
        assert_eq!(archive.selected_project_roots, vec![String::new()]);
        assert_eq!(
            archive.project_selection,
            ProjectSelection::Single {
                root: String::new()
            }
        );
    }

    #[test]
    fn project_roots_for_multi_project_gateway_are_sorted() {
        let archive = inspect_archive(&fixture_path("multi-project.gwbk"))
            .expect("fixture should be inspectable");
        assert_eq!(
            archive.detected_project_roots,
            vec![
                "projects/IADemo/".to_string(),
                "projects/OnlineDemo/".to_string(),
                "projects/TagDashboard/".to_string(),
                "projects/building-management-system-demo/".to_string(),
                "projects/global/".to_string(),
                "projects/oil-and-gas-demo/".to_string(),
                "projects/prepared-foods-line-demo/".to_string(),
                "projects/samplequickstart/".to_string(),
            ]
        );
        assert_eq!(
            archive.detected_project_roots,
            archive.selected_project_roots
        );
        assert_eq!(
            archive.project_selection,
            ProjectSelection::Multiple {
                roots: vec![
                    "projects/IADemo/".to_string(),
                    "projects/OnlineDemo/".to_string(),
                    "projects/TagDashboard/".to_string(),
                    "projects/building-management-system-demo/".to_string(),
                    "projects/global/".to_string(),
                    "projects/oil-and-gas-demo/".to_string(),
                    "projects/prepared-foods-line-demo/".to_string(),
                    "projects/samplequickstart/".to_string(),
                ]
            }
        );
    }

    #[test]
    fn archive_kind_prefers_root_project_when_both_shapes_exist() {
        let entries = vec![
            "project.json".to_string(),
            "projects/alpha/project.json".to_string(),
        ];
        assert_eq!(detect_archive_kind(&entries), ArchiveKind::ProjectExport);
    }

    #[test]
    fn project_roots_ignore_invalid_gateway_layouts() {
        let entries = vec![
            "projects//project.json".to_string(),
            "projects/alpha/nested/project.json".to_string(),
            "Projects/uppercase/project.json".to_string(),
            "projects/valid/project.json".to_string(),
        ];

        assert_eq!(
            detect_gateway_project_roots(&entries),
            vec!["projects/valid/".to_string()]
        );
    }

    #[test]
    fn project_meta_project_export_fixture_yields_single_record() {
        let archive_path = fixture_path("Template_v8.3_example.zip");
        let inspection = inspect_archive(&archive_path).expect("fixture should be inspectable");
        let project_meta =
            parse_project_metadata(&archive_path, &inspection.selected_project_roots).unwrap();

        assert_eq!(project_meta.len(), 1);
        assert_eq!(project_meta[0].project_root, "");
        assert_eq!(project_meta[0].title, "Good template");
        assert_eq!(project_meta[0].enabled, true);
        assert_eq!(project_meta[0].inheritable, false);
    }

    #[test]
    fn project_meta_multi_project_fixture_preserves_selected_root_order() {
        let archive_path = fixture_path("multi-project.gwbk");
        let selected_roots = vec![
            "projects/TagDashboard/".to_string(),
            "projects/IADemo/".to_string(),
        ];
        let project_meta = parse_project_metadata(&archive_path, &selected_roots).unwrap();

        assert_eq!(project_meta.len(), 2);
        assert_eq!(project_meta[0].project_root, "projects/TagDashboard/");
        assert_eq!(project_meta[0].title, "IIoT Demo");
        assert_eq!(project_meta[1].project_root, "projects/IADemo/");
        assert_eq!(project_meta[1].title, "Vision Demo");
    }

    #[test]
    fn project_meta_invalid_json_returns_json_parse_error() {
        let err = parse_project_json_bytes(
            Path::new("synthetic.zip"),
            "project.json",
            br#"{"title":"bad","enabled":"not_a_bool"}"#,
        )
        .expect_err("invalid JSON shape should fail");

        match err {
            AppError::JsonParse { .. } => {}
            other => panic!("expected json parse error, got: {other:?}"),
        }
    }

    #[test]
    fn resource_discovery_project_export_counts_expected_resources() {
        let archive_path = fixture_path("Template_v8.3_example.zip");
        let resources = discover_resources_for_root(&archive_path, "").unwrap();

        assert_eq!(resources.len(), 88);
        assert!(
            resources
                .iter()
                .all(|resource| resource.files.first().unwrap().file_kind == "resource.json")
        );
    }

    #[test]
    fn resource_discovery_gateway_backup_counts_expected_resources_per_project() {
        let archive_path = fixture_path("multi-project.gwbk");
        let selected_roots = vec![
            "projects/IADemo/".to_string(),
            "projects/OnlineDemo/".to_string(),
            "projects/TagDashboard/".to_string(),
            "projects/building-management-system-demo/".to_string(),
            "projects/global/".to_string(),
            "projects/oil-and-gas-demo/".to_string(),
            "projects/prepared-foods-line-demo/".to_string(),
            "projects/samplequickstart/".to_string(),
        ];

        let inventory = discover_resources_for_roots(&archive_path, &selected_roots).unwrap();
        let counts: Vec<(String, usize)> = inventory
            .into_iter()
            .map(|entry| (entry.project_root, entry.resources.len()))
            .collect();

        assert_eq!(
            counts,
            vec![
                ("projects/IADemo/".to_string(), 135),
                ("projects/OnlineDemo/".to_string(), 688),
                ("projects/TagDashboard/".to_string(), 76),
                ("projects/building-management-system-demo/".to_string(), 216),
                ("projects/global/".to_string(), 10),
                ("projects/oil-and-gas-demo/".to_string(), 24),
                ("projects/prepared-foods-line-demo/".to_string(), 132),
                ("projects/samplequickstart/".to_string(), 243),
            ]
        );
    }

    #[test]
    fn resource_discovery_is_deterministic_between_runs() {
        let archive_path = fixture_path("Template_v8.3_example.zip");
        let first = discover_resources_for_root(&archive_path, "").unwrap();
        let second = discover_resources_for_root(&archive_path, "").unwrap();

        assert_eq!(first, second);
    }

    #[test]
    fn resource_validation_rejects_missing_files_key() {
        let err = parse_resource(
            Path::new("synthetic.zip"),
            "foo/resource.json",
            br#"{"scope":"A"}"#,
        )
        .expect_err("missing files key should fail");

        match err {
            AppError::ResourceIntegrity { .. } => {}
            other => panic!("expected resource integrity error, got: {other:?}"),
        }
    }

    #[test]
    fn resource_validation_rejects_invalid_files_type() {
        let err = parse_resource(
            Path::new("synthetic.zip"),
            "foo/resource.json",
            br#"{"files":"not-an-array"}"#,
        )
        .expect_err("invalid files type should fail");

        match err {
            AppError::ResourceIntegrity { .. } => {}
            other => panic!("expected resource integrity error, got: {other:?}"),
        }
    }

    #[test]
    fn resource_validation_rejects_missing_declared_file() {
        let entry_set: BTreeSet<String> = ["foo/resource.json".to_string()].into_iter().collect();
        let err = build_resource_files(
            Path::new("synthetic.zip"),
            "foo/resource.json",
            &["missing.py".to_string()],
            &entry_set,
        )
        .expect_err("missing declared file should fail");

        match err {
            AppError::ResourceIntegrity { .. } => {}
            other => panic!("expected resource integrity error, got: {other:?}"),
        }
    }

    #[test]
    fn resource_validation_appends_data_bin_when_undeclared() {
        let entry_set: BTreeSet<String> = [
            "foo/resource.json".to_string(),
            "foo/view.json".to_string(),
            "foo/data.bin".to_string(),
        ]
        .into_iter()
        .collect();

        let files = build_resource_files(
            Path::new("synthetic.zip"),
            "foo/resource.json",
            &["view.json".to_string()],
            &entry_set,
        )
        .expect("build resource files should succeed");

        let ordered_paths: Vec<&str> = files
            .iter()
            .map(|file| file.file_zip_path.as_str())
            .collect();
        assert_eq!(
            ordered_paths,
            vec!["foo/resource.json", "foo/view.json", "foo/data.bin"]
        );
    }

    #[test]
    fn resource_validation_does_not_duplicate_declared_data_bin() {
        let entry_set: BTreeSet<String> =
            ["foo/resource.json".to_string(), "foo/data.bin".to_string()]
                .into_iter()
                .collect();

        let files = build_resource_files(
            Path::new("synthetic.zip"),
            "foo/resource.json",
            &["data.bin".to_string()],
            &entry_set,
        )
        .expect("build resource files should succeed");

        assert_eq!(files.len(), 2);
        assert_eq!(files[1].file_zip_path, "foo/data.bin");
    }

    #[test]
    fn resource_binary_only_detection_requires_only_data_bin_payload() {
        let entry_set: BTreeSet<String> =
            ["foo/resource.json".to_string(), "foo/data.bin".to_string()]
                .into_iter()
                .collect();
        let files = build_resource_files(
            Path::new("synthetic.zip"),
            "foo/resource.json",
            &["data.bin".to_string()],
            &entry_set,
        )
        .unwrap();
        assert!(is_binary_only_resource(&files));

        let entry_set_with_text: BTreeSet<String> = [
            "bar/resource.json".to_string(),
            "bar/data.bin".to_string(),
            "bar/view.json".to_string(),
        ]
        .into_iter()
        .collect();
        let files_with_text = build_resource_files(
            Path::new("synthetic.zip"),
            "bar/resource.json",
            &["view.json".to_string()],
            &entry_set_with_text,
        )
        .unwrap();
        assert!(!is_binary_only_resource(&files_with_text));
    }

    #[test]
    fn classifier_covers_all_baseline_type_keys() {
        let cases = vec![
            (
                "com.inductiveautomation.perspective/views/Main",
                "Perspective",
                "perspective.view",
            ),
            (
                "com.inductiveautomation.perspective/page-config",
                "Perspective",
                "perspective.page_config",
            ),
            (
                "com.inductiveautomation.perspective/style-classes/theme/default",
                "Perspective",
                "perspective.style_class",
            ),
            (
                "com.inductiveautomation.perspective/stylesheet",
                "Perspective",
                "perspective.stylesheet",
            ),
            (
                "com.inductiveautomation.perspective/message/toast",
                "Perspective",
                "perspective.message_handler",
            ),
            (
                "com.inductiveautomation.perspective/form-submission-handler/Form A",
                "Perspective",
                "perspective.form_submission_handler",
            ),
            (
                "com.inductiveautomation.perspective/key-event/Key A",
                "Perspective",
                "perspective.key_event",
            ),
            (
                "com.inductiveautomation.perspective/startup",
                "Perspective",
                "perspective.startup",
            ),
            (
                "com.inductiveautomation.perspective/shutdown",
                "Perspective",
                "perspective.shutdown",
            ),
            (
                "com.inductiveautomation.perspective/accelerometer",
                "Perspective",
                "perspective.accelerometer",
            ),
            (
                "com.inductiveautomation.perspective/barcode",
                "Perspective",
                "perspective.barcode",
            ),
            (
                "com.inductiveautomation.perspective/bluetooth",
                "Perspective",
                "perspective.bluetooth",
            ),
            (
                "com.inductiveautomation.perspective/auth-challenge",
                "Perspective",
                "perspective.auth_challenge",
            ),
            (
                "com.inductiveautomation.perspective/nfc-scan",
                "Perspective",
                "perspective.nfc_scan",
            ),
            (
                "com.inductiveautomation.perspective/page-startup",
                "Perspective",
                "perspective.page_startup",
            ),
            (
                "com.inductiveautomation.perspective/session-props",
                "Perspective",
                "perspective.session_props",
            ),
            (
                "ignition/script-python/my/script",
                "Scripting",
                "script.python",
            ),
            (
                "ignition/timer/My Timer",
                "Scripting",
                "script.gateway_event",
            ),
            (
                "ignition/named-query/My Query",
                "Named Queries",
                "named_query",
            ),
            (
                "com.inductiveautomation.sfc/charts/Main",
                "Sequential Function Charts (SFC)",
                "sfc",
            ),
            (
                "com.inductiveautomation.eventstream/event-streams/Main",
                "Event Streams",
                "event_stream",
            ),
            (
                "com.inductiveautomation.reporting/reports/Main",
                "Reports",
                "report",
            ),
            (
                "com.inductiveautomation.alarm-notification/alarm-pipelines/Main",
                "Alarm Notification Pipelines",
                "alarm_pipeline",
            ),
            ("ignition/global-props", "Properties", "project_properties"),
        ];

        for (path, expected_section, expected_type_key) in cases {
            let classification = classify_resource_path(path);
            assert_eq!(
                classification.section, expected_section,
                "section mismatch for path `{path}`"
            );
            assert_eq!(
                classification.type_key, expected_type_key,
                "type mismatch for path `{path}`"
            );
        }
    }

    #[test]
    fn classifier_uses_unknown_fallback_when_no_rule_matches() {
        let classification = classify_resource_path("com.inductiveautomation.vision/windows/Main");
        assert_eq!(classification.section, "Other");
        assert_eq!(classification.type_key, "unknown");
    }

    #[test]
    fn coverage_metrics_counts_unknown_resources() {
        let resources = vec![
            synthetic_resource(
                "Perspective",
                "perspective.view",
                "a",
                false,
                &["resource.json"],
            ),
            synthetic_resource(
                "Other",
                "unknown",
                "b",
                true,
                &["resource.json", "data.bin"],
            ),
            synthetic_resource(
                "Other",
                "unknown",
                "c",
                false,
                &["resource.json", "view.json"],
            ),
        ];

        let coverage = compute_coverage(&resources);
        assert_eq!(coverage.unknown_resources, 2);
        assert!((coverage.unknown_ratio - (2.0 / 3.0)).abs() < f64::EPSILON);
    }

    #[test]
    fn project_counts_aggregates_resources_files_and_maps() {
        let resources = vec![
            synthetic_resource(
                "Perspective",
                "perspective.view",
                "com.inductiveautomation.perspective/views/Main",
                false,
                &["resource.json", "view.json"],
            ),
            synthetic_resource(
                "Scripting",
                "script.python",
                "ignition/script-python/a",
                false,
                &["resource.json", "script"],
            ),
            synthetic_resource(
                "Other",
                "unknown",
                "com.inductiveautomation.vision/windows/Main",
                true,
                &["resource.json", "data.bin"],
            ),
        ];

        let counts = compute_project_counts(&resources);
        assert_eq!(counts.resources_total, 3);
        assert_eq!(counts.files_total, 6);
        assert_eq!(counts.binary_only_resources, 1);

        assert_eq!(
            counts.resources_by_section,
            BTreeMap::from([
                ("Other".to_string(), 1usize),
                ("Perspective".to_string(), 1usize),
                ("Scripting".to_string(), 1usize),
            ])
        );
        assert_eq!(
            counts.resources_by_type,
            BTreeMap::from([
                ("perspective.view".to_string(), 1usize),
                ("script.python".to_string(), 1usize),
                ("unknown".to_string(), 1usize),
            ])
        );
        assert_eq!(
            counts.files_by_kind,
            BTreeMap::from([
                ("data.bin".to_string(), 1usize),
                ("resource.json".to_string(), 3usize),
                ("script".to_string(), 1usize),
                ("view.json".to_string(), 1usize),
            ])
        );
    }

    #[test]
    fn analytics_schema_has_parity_between_project_export_and_gateway_inputs() {
        let project_export_path = fixture_path("Template_v8.3_example.zip");
        let project_export_inspection = inspect_archive(&project_export_path).unwrap();
        let project_export_meta = parse_project_metadata(
            &project_export_path,
            &project_export_inspection.selected_project_roots,
        )
        .unwrap();
        let project_export_resources = discover_resources_for_roots(
            &project_export_path,
            &project_export_inspection.selected_project_roots,
        )
        .unwrap();
        let project_export_bundle = build_analytics_bundle(
            &project_export_path,
            "2026-03-10T00:00:00Z",
            &project_export_inspection,
            &project_export_meta,
            &project_export_resources,
        )
        .unwrap();

        let gateway_path = fixture_path("multi-project.gwbk");
        let gateway_inspection = inspect_archive(&gateway_path).unwrap();
        let gateway_meta =
            parse_project_metadata(&gateway_path, &gateway_inspection.selected_project_roots)
                .unwrap();
        let gateway_resources =
            discover_resources_for_roots(&gateway_path, &gateway_inspection.selected_project_roots)
                .unwrap();
        let gateway_bundle = build_analytics_bundle(
            &gateway_path,
            "2026-03-10T00:00:00Z",
            &gateway_inspection,
            &gateway_meta,
            &gateway_resources,
        )
        .unwrap();

        let project_export_value = serde_json::to_value(project_export_bundle).unwrap();
        let gateway_value = serde_json::to_value(gateway_bundle).unwrap();

        let project_export_keys: BTreeSet<String> = project_export_value
            .as_object()
            .unwrap()
            .keys()
            .cloned()
            .collect();
        let gateway_keys: BTreeSet<String> =
            gateway_value.as_object().unwrap().keys().cloned().collect();

        assert_eq!(project_export_keys, gateway_keys);
        assert_eq!(
            project_export_keys,
            BTreeSet::from([
                "generated_at".to_string(),
                "input".to_string(),
                "issues".to_string(),
                "projects".to_string(),
                "schema_version".to_string(),
                "summary".to_string(),
            ])
        );
    }

    #[test]
    fn analytics_aggregation_matches_project_entries_for_multi_project_fixture() {
        let gateway_path = fixture_path("multi-project.gwbk");
        let inspection = inspect_archive(&gateway_path).unwrap();
        let project_meta =
            parse_project_metadata(&gateway_path, &inspection.selected_project_roots).unwrap();
        let resources =
            discover_resources_for_roots(&gateway_path, &inspection.selected_project_roots)
                .unwrap();
        let bundle = build_analytics_bundle(
            &gateway_path,
            "2026-03-10T00:00:00Z",
            &inspection,
            &project_meta,
            &resources,
        )
        .unwrap();

        assert_eq!(bundle.projects.len(), 8);
        let roots: Vec<String> = bundle
            .projects
            .iter()
            .map(|project| project.project_root.clone())
            .collect();
        let mut sorted_roots = roots.clone();
        sorted_roots.sort();
        assert_eq!(roots, sorted_roots);

        let resources_total_from_projects: usize = bundle
            .projects
            .iter()
            .map(|project| project.counts.resources_total)
            .sum();
        let files_total_from_projects: usize = bundle
            .projects
            .iter()
            .map(|project| project.counts.files_total)
            .sum();
        let binary_total_from_projects: usize = bundle
            .projects
            .iter()
            .map(|project| project.counts.binary_only_resources)
            .sum();
        let unknown_total_from_projects: usize = bundle
            .projects
            .iter()
            .map(|project| project.coverage.unknown_resources)
            .sum();

        assert_eq!(bundle.summary.projects_total, bundle.projects.len());
        assert_eq!(
            bundle.summary.resources_total,
            resources_total_from_projects
        );
        assert_eq!(bundle.summary.files_total, files_total_from_projects);
        assert_eq!(
            bundle.summary.binary_only_resources,
            binary_total_from_projects
        );
        assert_eq!(
            bundle.summary.unknown_resources,
            unknown_total_from_projects
        );

        let expected_ratio = if resources_total_from_projects == 0 {
            0.0
        } else {
            unknown_total_from_projects as f64 / resources_total_from_projects as f64
        };
        assert!((bundle.summary.unknown_ratio - expected_ratio).abs() < f64::EPSILON);
    }

    #[test]
    fn analytics_aggregation_function_merges_maps_deterministically() {
        let project_a = super::ProjectAnalytics {
            project_root: "a".to_string(),
            project: super::ProjectMetadata {
                project_root: "a".to_string(),
                title: "A".to_string(),
                description: None,
                parent: None,
                enabled: true,
                inheritable: false,
            },
            counts: super::ProjectCounts {
                resources_total: 1,
                files_total: 2,
                binary_only_resources: 0,
                resources_by_section: BTreeMap::from([("Perspective".to_string(), 1usize)]),
                resources_by_type: BTreeMap::from([("perspective.view".to_string(), 1usize)]),
                files_by_kind: BTreeMap::from([
                    ("resource.json".to_string(), 1usize),
                    ("view.json".to_string(), 1usize),
                ]),
            },
            coverage: super::CoverageMetrics {
                unknown_resources: 0,
                unknown_ratio: 0.0,
            },
            issues: vec![],
        };
        let project_b = super::ProjectAnalytics {
            project_root: "b".to_string(),
            project: super::ProjectMetadata {
                project_root: "b".to_string(),
                title: "B".to_string(),
                description: None,
                parent: None,
                enabled: true,
                inheritable: false,
            },
            counts: super::ProjectCounts {
                resources_total: 2,
                files_total: 3,
                binary_only_resources: 1,
                resources_by_section: BTreeMap::from([
                    ("Other".to_string(), 1usize),
                    ("Scripting".to_string(), 1usize),
                ]),
                resources_by_type: BTreeMap::from([
                    ("script.python".to_string(), 1usize),
                    ("unknown".to_string(), 1usize),
                ]),
                files_by_kind: BTreeMap::from([
                    ("data.bin".to_string(), 1usize),
                    ("resource.json".to_string(), 2usize),
                ]),
            },
            coverage: super::CoverageMetrics {
                unknown_resources: 1,
                unknown_ratio: 0.5,
            },
            issues: vec![],
        };

        let summary = aggregate_summary(&[project_a, project_b]);

        assert_eq!(summary.projects_total, 2);
        assert_eq!(summary.resources_total, 3);
        assert_eq!(summary.files_total, 5);
        assert_eq!(summary.binary_only_resources, 1);
        assert_eq!(summary.unknown_resources, 1);
        assert!((summary.unknown_ratio - (1.0 / 3.0)).abs() < f64::EPSILON);
        assert_eq!(
            summary.resources_by_section,
            BTreeMap::from([
                ("Other".to_string(), 1usize),
                ("Perspective".to_string(), 1usize),
                ("Scripting".to_string(), 1usize),
            ])
        );
        assert_eq!(
            summary.resources_by_type,
            BTreeMap::from([
                ("perspective.view".to_string(), 1usize),
                ("script.python".to_string(), 1usize),
                ("unknown".to_string(), 1usize),
            ])
        );
        assert_eq!(
            summary.files_by_kind,
            BTreeMap::from([
                ("data.bin".to_string(), 1usize),
                ("resource.json".to_string(), 3usize),
                ("view.json".to_string(), 1usize),
            ])
        );
    }
}