surtgis 0.6.24

High-performance geospatial analysis CLI
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
//! CLI command and subcommand definitions.

use clap::{Parser, Subcommand};
use std::path::PathBuf;

// ─── CLI structure ──────────────────────────────────────────────────────

#[derive(Parser)]
#[command(name = "surtgis")]
#[command(author, version, about = "High-performance geospatial analysis", long_about = None)]
#[command(allow_negative_numbers = true)]
pub struct Cli {
    /// Verbose output
    #[arg(short, long, global = true)]
    pub verbose: bool,

    /// Compress output GeoTIFFs (deflate)
    #[arg(long, global = true)]
    pub compress: bool,

    /// Force streaming mode for large rasters (auto-detected if >500MB)
    #[arg(long, global = true)]
    pub streaming: bool,

    /// Maximum memory to use (e.g., 4G, 1024MB, 500MiB).
    /// If raster would exceed this when decompressed, force streaming.
    #[arg(long, global = true)]
    pub max_memory: Option<String>,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Show information about a raster file
    Info {
        /// Input raster file
        input: PathBuf,
    },
    /// Terrain analysis algorithms
    Terrain {
        #[command(subcommand)]
        algorithm: TerrainCommands,
    },
    /// Hydrology algorithms
    Hydrology {
        #[command(subcommand)]
        algorithm: HydrologyCommands,
    },
    /// Imagery / spectral index algorithms
    Imagery {
        #[command(subcommand)]
        algorithm: ImageryCommands,
    },
    /// Mathematical morphology algorithms
    Morphology {
        #[command(subcommand)]
        algorithm: MorphologyCommands,
    },
    /// Landscape ecology metrics (global patch/class/landscape level)
    Landscape {
        #[command(subcommand)]
        algorithm: LandscapeCommands,
    },
    /// Extract raster values at point locations to CSV
    Extract {
        /// Directory with features.json and feature rasters (from `pipeline features`)
        #[arg(long)]
        features_dir: PathBuf,
        /// Vector file with labeled points (.geojson, .shp, .gpkg)
        #[arg(long)]
        points: PathBuf,
        /// Property name containing the target label/value
        #[arg(long)]
        target: String,
        /// Output CSV file
        output: PathBuf,
    },
    /// Clip a raster by polygon or bounding box
    Clip {
        /// Input raster file
        input: PathBuf,
        /// Vector file with polygon(s) (.geojson, .shp, .gpkg)
        #[arg(long)]
        polygon: Option<PathBuf>,
        /// Bounding box: xmin,ymin,xmax,ymax (same CRS as input)
        #[arg(long)]
        bbox: Option<String>,
        /// Output file
        output: PathBuf,
    },
    /// Rasterize a vector file to a raster grid (.geojson, .shp, .gpkg)
    Rasterize {
        /// Input vector file (.geojson, .shp, .gpkg)
        input: PathBuf,
        /// Output raster file
        output: PathBuf,
        /// Reference raster for grid dimensions and transform
        #[arg(long)]
        reference: PathBuf,
        /// Property to use as raster value (default: sequential 1..N)
        #[arg(long)]
        attribute: Option<String>,
    },
    /// Resample a raster to match the grid of a reference raster
    Resample {
        /// Input raster to resample
        input: PathBuf,
        /// Output resampled raster
        output: PathBuf,
        /// Reference raster defining the target grid
        #[arg(long)]
        reference: PathBuf,
        /// Interpolation method: nearest or bilinear
        #[arg(short, long, default_value = "bilinear")]
        method: String,
    },
    /// Mosaic multiple rasters into one covering the union extent
    Mosaic {
        /// Input raster files (at least 2)
        #[arg(short, long, required = true)]
        input: Vec<PathBuf>,
        /// Output GeoTIFF file
        output: PathBuf,
    },
    /// Read and process Cloud Optimized GeoTIFFs (COGs) via HTTP
    #[cfg(feature = "cloud")]
    Cog {
        #[command(subcommand)]
        action: CogCommands,
    },
    /// Search and fetch data from STAC catalogs (Planetary Computer, Earth Search)
    #[cfg(feature = "cloud")]
    Stac {
        #[command(subcommand)]
        action: StacCommands,
    },
    /// Pipeline: integrated workflows for specific use cases
    Pipeline {
        #[command(subcommand)]
        action: PipelineCommands,
    },
    /// Vector geoprocessing: intersection, union, difference, dissolve, buffer
    Vector {
        #[command(subcommand)]
        action: VectorCommands,
    },
    /// Geostatistical interpolation: variogram, kriging, universal kriging, regression kriging
    Interpolation {
        #[command(subcommand)]
        action: InterpolationCommands,
    },
    /// Temporal analysis: trend, anomaly, phenology, statistics
    Temporal {
        #[command(subcommand)]
        action: TemporalCommands,
    },
    /// Classification: unsupervised/supervised raster classification (k-means, PCA, etc.)
    Classification {
        #[command(subcommand)]
        algorithm: ClassificationCommands,
    },
    /// Texture analysis: edge detection and GLCM texture measures
    Texture {
        #[command(subcommand)]
        algorithm: TextureCommands,
    },
    /// Statistics: focal, zonal, and spatial autocorrelation
    Statistics {
        #[command(subcommand)]
        algorithm: StatisticsCommands,
    },
    /// Machine learning: train, predict, and benchmark classifiers on geospatial features
    #[cfg(feature = "ml")]
    Ml {
        #[command(subcommand)]
        action: MlCommands,
    },
}

// ─── Terrain subcommands ────────────────────────────────────────────────

#[derive(Subcommand)]
pub enum TerrainCommands {
    /// Calculate slope from DEM
    Slope {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Output units: degrees, percent, radians
        #[arg(short, long, default_value = "degrees")]
        units: String,
        /// Z-factor for unit conversion
        #[arg(short, long, default_value = "1.0")]
        z_factor: f64,
    },
    /// Calculate aspect from DEM
    Aspect {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Output format: degrees, radians, compass
        #[arg(short, long, default_value = "degrees")]
        format: String,
    },
    /// Calculate hillshade from DEM
    Hillshade {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Sun azimuth in degrees (0=North, clockwise)
        #[arg(short, long, default_value = "315")]
        azimuth: f64,
        /// Sun altitude in degrees above horizon
        #[arg(short = 'l', long, default_value = "45")]
        altitude: f64,
        /// Z-factor for vertical exaggeration
        #[arg(short, long, default_value = "1.0")]
        z_factor: f64,
    },
    /// Calculate surface curvature from DEM
    Curvature {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Curvature type: general, profile, plan
        #[arg(short = 't', long, default_value = "general")]
        curvature_type: String,
        /// Z-factor for unit conversion
        #[arg(short, long, default_value = "1.0")]
        z_factor: f64,
    },
    /// Calculate Topographic Position Index
    Tpi {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Calculate Terrain Ruggedness Index
    Tri {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Landform classification (multi-scale TPI + slope)
    Landform {
        /// Input DEM file
        input: PathBuf,
        /// Output file (class codes 1-11)
        output: PathBuf,
        /// Small-scale TPI radius
        #[arg(long, default_value = "3")]
        small_radius: usize,
        /// Large-scale TPI radius
        #[arg(long, default_value = "10")]
        large_radius: usize,
        /// Standardized TPI threshold (z-score)
        #[arg(long, default_value = "1.0")]
        threshold: f64,
        /// Slope threshold (degrees) for gentle/steep
        #[arg(long, default_value = "6.0")]
        slope_threshold: f64,
    },
    /// Geomorphon landform classification (Jasiewicz & Stepinski 2013)
    Geomorphons {
        input: PathBuf,
        output: PathBuf,
        /// Lookup radius in cells
        #[arg(short, long, default_value = "10")]
        radius: usize,
        /// Flatness threshold in degrees
        #[arg(short, long, default_value = "1.0")]
        flatness: f64,
    },
    /// Northness: cos(aspect), north-facing = 1, south-facing = -1
    Northness {
        input: PathBuf,
        output: PathBuf,
    },
    /// Eastness: sin(aspect), east-facing = 1, west-facing = -1
    Eastness {
        input: PathBuf,
        output: PathBuf,
    },
    /// Positive topographic openness (sky visibility above)
    OpennessPositive {
        input: PathBuf,
        output: PathBuf,
        /// Search radius in cells
        #[arg(short, long, default_value = "10")]
        radius: usize,
        /// Number of azimuth directions
        #[arg(short, long, default_value = "8")]
        directions: usize,
    },
    /// Negative topographic openness (enclosure below)
    OpennessNegative {
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "10")]
        radius: usize,
        #[arg(short, long, default_value = "8")]
        directions: usize,
    },
    /// Sky View Factor (0=enclosed, 1=flat horizon)
    Svf {
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "10")]
        radius: usize,
        #[arg(short, long, default_value = "16")]
        directions: usize,
    },
    /// MRVBF/MRRTF: Multi-Resolution Valley/Ridge Bottom Flatness
    Mrvbf {
        input: PathBuf,
        /// Output MRVBF file
        output: PathBuf,
        /// Optional MRRTF output file
        #[arg(long)]
        mrrtf_output: Option<PathBuf>,
    },
    /// Deviation from Mean Elevation
    Dev {
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "10")]
        radius: usize,
    },
    /// Vector Ruggedness Measure
    Vrm {
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Florinsky advanced curvature (14 types)
    AdvancedCurvature {
        input: PathBuf,
        output: PathBuf,
        /// Curvature type: mean_h|mean, gaussian_k|gaussian, kmin|minimal, kmax|maximal, kh|horizontal, kv|vertical, khe|horizontal_excess, kve|vertical_excess, ka|accumulation, kr|ring, rotor, laplacian, unsphericity, difference
        #[arg(short = 't', long, default_value = "mean_h")]
        curvature_type: String,
    },
    /// Viewshed: binary line-of-sight visibility from an observer point
    Viewshed {
        input: PathBuf,
        output: PathBuf,
        /// Observer row (pixel coordinate)
        #[arg(long)]
        observer_row: usize,
        /// Observer column (pixel coordinate)
        #[arg(long)]
        observer_col: usize,
        /// Observer height above ground (meters)
        #[arg(long, default_value = "1.8")]
        observer_height: f64,
        /// Target height above ground (meters)
        #[arg(long, default_value = "0.0")]
        target_height: f64,
        /// Maximum visibility radius in cells (0 = unlimited)
        #[arg(long, default_value = "0")]
        max_radius: usize,
    },
    /// Convergence Index (-100=convergent, +100=divergent)
    Convergence {
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "3")]
        radius: usize,
    },
    /// Multi-directional hillshade (6 azimuths combined)
    MultiHillshade {
        input: PathBuf,
        output: PathBuf,
    },
    /// LS-Factor for RUSLE soil erosion model
    LsFactor {
        /// Flow accumulation raster
        #[arg(long)]
        flow_acc: PathBuf,
        /// Slope raster (radians)
        #[arg(long)]
        slope: PathBuf,
        /// Output file
        output: PathBuf,
        /// Cell size in meters
        #[arg(long, default_value = "1.0")]
        cell_size: f64,
    },
    /// Valley depth: vertical distance to ridge surface
    ValleyDepth {
        input: PathBuf,
        output: PathBuf,
    },
    /// Relative Slope Position (0=valley, 1=ridge)
    RelativeSlopePosition {
        /// HAND raster
        #[arg(long)]
        hand: PathBuf,
        /// Valley depth raster
        #[arg(long)]
        valley_depth: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// Surface Area Ratio (3D/2D area roughness)
    SurfaceAreaRatio {
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Compute all standard terrain factors in one pass
    All {
        /// Input DEM file
        input: PathBuf,
        /// Output directory for all terrain products
        #[arg(short, long)]
        outdir: PathBuf,
    },
    /// Solar radiation (clear-sky insolation for a given day/hour)
    SolarRadiation {
        input: PathBuf,
        output: PathBuf,
        /// Day of year (1-365)
        #[arg(long)]
        day: u32,
        /// Hour (solar time, 0-24)
        #[arg(long)]
        hour: f64,
        /// Latitude in degrees (negative for southern hemisphere)
        #[arg(long, allow_hyphen_values = true)]
        latitude: f64,
    },
    /// Annual solar radiation (integrated over full year)
    SolarRadiationAnnual {
        input: PathBuf,
        output: PathBuf,
        /// Latitude in degrees (negative for southern hemisphere)
        #[arg(long, allow_hyphen_values = true)]
        latitude: f64,
    },
    /// Contour lines as raster
    ContourLines {
        input: PathBuf,
        output: PathBuf,
        /// Contour interval
        #[arg(long, default_value = "100")]
        interval: f64,
        /// Base contour value
        #[arg(long, default_value = "0")]
        base: f64,
    },
    /// Cost distance from source points
    CostDistance {
        /// Cost surface raster
        input: PathBuf,
        /// Source points raster (non-zero = source)
        #[arg(long)]
        sources: PathBuf,
        /// Output accumulated cost raster
        output: PathBuf,
    },
    /// Shape index (concavity/convexity, -1 to +1)
    ShapeIndex {
        input: PathBuf,
        output: PathBuf,
    },
    /// Curvedness (magnitude of curvature)
    Curvedness {
        input: PathBuf,
        output: PathBuf,
    },
    /// Gaussian smoothing
    GaussianSmoothing {
        input: PathBuf,
        output: PathBuf,
        /// Sigma (standard deviation in cells)
        #[arg(long, default_value = "1.0")]
        sigma: f64,
        /// Kernel radius in cells (default: ceil(3*sigma))
        #[arg(long)]
        radius: Option<usize>,
    },
    /// Feature-preserving smoothing (edge-aware)
    FeaturePreservingSmoothing {
        input: PathBuf,
        output: PathBuf,
        /// Smoothing strength
        #[arg(long, default_value = "1.0")]
        strength: f64,
        /// Number of iterations
        #[arg(long, default_value = "3")]
        iterations: usize,
    },
    /// Wind exposure index
    WindExposure {
        input: PathBuf,
        output: PathBuf,
        /// Wind direction in degrees from north (0=N, 90=E)
        #[arg(long, default_value = "270")]
        direction: f64,
        /// Search radius in cells
        #[arg(long, default_value = "100")]
        radius: usize,
    },
    /// Horizon angles for a given azimuth
    HorizonAngle {
        input: PathBuf,
        output: PathBuf,
        /// Azimuth in degrees from north
        #[arg(long, default_value = "180")]
        azimuth: f64,
        /// Search radius in cells
        #[arg(long, default_value = "100")]
        radius: usize,
    },
    /// Accumulation zones (contributing area classification)
    AccumulationZones {
        input: PathBuf,
        output: PathBuf,
    },
    /// Stream Power Index (SPI = A × tan(slope))
    Spi {
        /// Flow accumulation raster
        #[arg(long)]
        flow_acc: PathBuf,
        /// Slope raster (radians)
        #[arg(long)]
        slope: PathBuf,
        output: PathBuf,
    },
    /// Sediment Transport Index (STI)
    Sti {
        /// Flow accumulation raster
        #[arg(long)]
        flow_acc: PathBuf,
        /// Slope raster (radians)
        #[arg(long)]
        slope: PathBuf,
        output: PathBuf,
    },
    /// Topographic Wetness Index (TWI = ln(A / tan(slope)))
    Twi {
        /// Flow accumulation raster
        #[arg(long)]
        flow_acc: PathBuf,
        /// Slope raster (radians)
        #[arg(long)]
        slope: PathBuf,
        output: PathBuf,
    },
    /// Log transform (ln(x+1))
    LogTransform {
        input: PathBuf,
        output: PathBuf,
    },
    /// DEM uncertainty analysis (Monte Carlo)
    Uncertainty {
        input: PathBuf,
        /// Output directory (mean, std, etc.)
        #[arg(short, long)]
        outdir: PathBuf,
        /// Error standard deviation (meters)
        #[arg(long, default_value = "1.0")]
        error_std: f64,
        /// Number of simulations
        #[arg(long, default_value = "100")]
        n_simulations: usize,
    },
    /// PDERL viewshed (reference plane algorithm)
    ViewshedPderl {
        input: PathBuf,
        output: PathBuf,
        /// Observer row
        #[arg(long)]
        row: usize,
        /// Observer column
        #[arg(long)]
        col: usize,
        /// Observer height above ground
        #[arg(long, default_value = "1.7")]
        height: f64,
    },
    /// XDraw viewshed (approximate, fast)
    ViewshedXdraw {
        input: PathBuf,
        output: PathBuf,
        /// Observer row
        #[arg(long)]
        row: usize,
        /// Observer column
        #[arg(long)]
        col: usize,
        /// Observer height above ground
        #[arg(long, default_value = "1.7")]
        height: f64,
    },
    /// Multiple-observer cumulative viewshed
    ViewshedMultiple {
        input: PathBuf,
        output: PathBuf,
        /// Observer locations as row,col pairs (e.g. "10,20;30,40;50,60")
        #[arg(long)]
        observers: String,
        /// Observer height above ground
        #[arg(long, default_value = "1.7")]
        height: f64,
    },
    /// Hypsometrically tinted hillshade (hillshade × normalized elevation)
    HypsometricHillshade {
        input: PathBuf,
        output: PathBuf,
        /// Sun azimuth in degrees
        #[arg(short, long, default_value = "315")]
        azimuth: f64,
        /// Sun altitude in degrees
        #[arg(short = 'l', long, default_value = "45")]
        altitude: f64,
        /// Z-factor
        #[arg(short, long, default_value = "1.0")]
        z_factor: f64,
    },
    /// Elevation relative to global min/max (normalized 0–1)
    ElevRelative {
        input: PathBuf,
        output: PathBuf,
    },
    /// Difference from mean elevation (non-normalized, in DEM units)
    DiffFromMean {
        input: PathBuf,
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "10")]
        radius: usize,
    },
    /// Percent elevation range (local position 0–100%)
    PercentElevRange {
        input: PathBuf,
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "10")]
        radius: usize,
    },
    /// Elevation above pit / depth in sink
    ElevAbovePit {
        input: PathBuf,
        output: PathBuf,
    },
    /// Circular variance of aspect (0=uniform, 1=dispersed)
    CircularVarianceAspect {
        input: PathBuf,
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "3")]
        radius: usize,
    },
    /// Neighbour elevation statistics (3×3 window, 5 outputs)
    Neighbours {
        input: PathBuf,
        /// Output path: directory (all 5 stats) or file (with --stat)
        #[arg(short, long)]
        output: PathBuf,
        /// Single statistic: max_downslope_change, min_downslope_change, max_upslope_change, num_downslope, num_upslope
        #[arg(long)]
        stat: Option<String>,
    },
    /// Pennock landform classification (7 classes)
    Pennock {
        input: PathBuf,
        output: PathBuf,
        /// Slope threshold (degrees) for "level" class
        #[arg(long, default_value = "3.0")]
        slope_threshold: f64,
        /// Profile curvature threshold for linear vs convex/concave
        #[arg(long, default_value = "0.1")]
        curv_threshold: f64,
    },
    /// Edge density (proportion of edge pixels in focal window)
    EdgeDensity {
        input: PathBuf,
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "3")]
        radius: usize,
        /// Sobel magnitude threshold for edge detection
        #[arg(short, long, default_value = "0.5")]
        threshold: f64,
    },
    /// Relative aspect (local vs regional aspect difference, 0–180°)
    RelativeAspect {
        input: PathBuf,
        output: PathBuf,
        /// Gaussian sigma for regional smoothing
        #[arg(long, default_value = "50")]
        sigma: f64,
    },
    /// Average normal vector angular deviation (degrees)
    NormalDeviation {
        input: PathBuf,
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "3")]
        radius: usize,
    },
    /// Spherical standard deviation of surface normals
    SphericalStdDev {
        input: PathBuf,
        output: PathBuf,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "3")]
        radius: usize,
    },
    /// Directional relief (elevation range along azimuth)
    DirectionalRelief {
        input: PathBuf,
        output: PathBuf,
        /// Search radius in cells
        #[arg(short, long, default_value = "10")]
        radius: usize,
        /// Azimuth in degrees (0 = multidirectional average)
        #[arg(short, long, default_value = "0")]
        azimuth: f64,
    },
    /// Downslope index (distance to reach elevation drop, Hjerdt 2004)
    DownslopeIndex {
        input: PathBuf,
        output: PathBuf,
        /// Elevation drop threshold in DEM units
        #[arg(short, long, default_value = "2.0")]
        drop: f64,
    },
    /// Maximum upstream branch length (longest D8 flow path)
    MaxBranchLength {
        input: PathBuf,
        output: PathBuf,
    },
}

// ─── Hydrology subcommands ──────────────────────────────────────────────

#[derive(Subcommand)]
pub enum HydrologyCommands {
    /// Fill sinks / depressions in DEM (Planchon-Darboux 2001)
    FillSinks {
        /// Input DEM file
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Minimum slope to enforce
        #[arg(long, default_value = "0.01")]
        min_slope: f64,
    },
    /// D8 flow direction from DEM
    FlowDirection {
        /// Input DEM file
        input: PathBuf,
        /// Output file (D8 codes: 1,2,4,8,16,32,64,128)
        output: PathBuf,
    },
    /// Flow accumulation from flow direction raster
    FlowAccumulation {
        /// Input flow direction raster (D8 codes)
        input: PathBuf,
        /// Output file (upstream cell count)
        output: PathBuf,
    },
    /// Watershed delineation from flow direction
    Watershed {
        /// Input flow direction raster (D8 codes)
        input: PathBuf,
        /// Output file (basin IDs)
        output: PathBuf,
        /// Pour points as "row,col;row,col;..."
        #[arg(long)]
        pour_points: String,
    },
    /// Priority-Flood depression filling (Barnes 2014, optimal O(n log n))
    PriorityFlood {
        input: PathBuf,
        output: PathBuf,
        /// Minimum slope epsilon
        #[arg(long, default_value = "0.0001")]
        epsilon: f64,
    },
    /// Breach depressions (carve channels through barriers)
    Breach {
        input: PathBuf,
        output: PathBuf,
        /// Maximum breach depth (meters)
        #[arg(long, default_value = "100.0")]
        max_depth: f64,
        /// Maximum breach length (cells)
        #[arg(long, default_value = "1000")]
        max_length: usize,
        /// Fill remaining unfilled depressions
        #[arg(long)]
        fill_remaining: bool,
    },
    /// D-infinity flow direction (Tarboton 1997, continuous angles)
    FlowDirectionDinf {
        input: PathBuf,
        output: PathBuf,
    },
    /// Multiple Flow Direction accumulation (Quinn et al. 1991)
    FlowAccumulationMfd {
        input: PathBuf,
        output: PathBuf,
        /// Flow partition exponent
        #[arg(long, default_value = "1.1")]
        exponent: f64,
    },
    /// Topographic Wetness Index (from DEM, full pipeline)
    Twi {
        /// Input DEM file
        input: PathBuf,
        output: PathBuf,
    },
    /// Height Above Nearest Drainage (from DEM, full pipeline)
    Hand {
        /// Input DEM file
        input: PathBuf,
        output: PathBuf,
        /// Stream extraction threshold (contributing cells)
        #[arg(long, default_value = "1000")]
        threshold: f64,
    },
    /// Stream network extraction (from DEM, full pipeline)
    StreamNetwork {
        /// Input DEM file
        input: PathBuf,
        output: PathBuf,
        /// Contributing area threshold
        #[arg(long, default_value = "1000")]
        threshold: f64,
    },
    /// Drainage density: stream length per unit area
    DrainageDensity {
        /// Stream network raster (binary: 1=stream)
        input: PathBuf,
        output: PathBuf,
        #[arg(short, long, default_value = "10")]
        radius: usize,
        #[arg(long, default_value = "1.0")]
        cell_size: f64,
    },
    /// Hypsometric integral per watershed
    HypsometricIntegral {
        /// DEM file
        #[arg(long)]
        dem: PathBuf,
        /// Watershed raster (i32 IDs)
        #[arg(long)]
        watersheds: PathBuf,
    },
    /// Sediment Connectivity Index (Borselli 2008)
    SedimentConnectivity {
        /// Slope raster (radians)
        #[arg(long)]
        slope: PathBuf,
        /// Flow accumulation raster
        #[arg(long)]
        flow_acc: PathBuf,
        /// D8 flow direction raster
        #[arg(long)]
        flow_dir: PathBuf,
        /// Output file
        output: PathBuf,
        /// Stream threshold (flow accumulation cells)
        #[arg(long, default_value = "1000")]
        threshold: f64,
    },
    /// Basin morphometric parameters per watershed
    BasinMorphometry {
        /// Watershed raster (i32 IDs)
        input: PathBuf,
        #[arg(long, default_value = "1.0")]
        cell_size: f64,
    },
    /// Compute full hydrology pipeline from DEM
    All {
        /// Input DEM file
        input: PathBuf,
        /// Output directory
        #[arg(short, long)]
        outdir: PathBuf,
        /// Stream threshold
        #[arg(long, default_value = "1000")]
        threshold: f64,
    },
}

// ─── Imagery subcommands ────────────────────────────────────────────────

#[derive(Subcommand)]
pub enum ImageryCommands {
    /// NDVI: Normalized Difference Vegetation Index
    Ndvi {
        /// NIR band file
        #[arg(long)]
        nir: PathBuf,
        /// Red band file
        #[arg(long)]
        red: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// NDWI: Normalized Difference Water Index
    Ndwi {
        /// Green band file
        #[arg(long)]
        green: PathBuf,
        /// NIR band file
        #[arg(long)]
        nir: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// MNDWI: Modified Normalized Difference Water Index
    Mndwi {
        /// Green band file
        #[arg(long)]
        green: PathBuf,
        /// SWIR band file
        #[arg(long)]
        swir: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// NBR: Normalized Burn Ratio
    Nbr {
        /// NIR band file
        #[arg(long)]
        nir: PathBuf,
        /// SWIR band file
        #[arg(long)]
        swir: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// SAVI: Soil-Adjusted Vegetation Index
    Savi {
        /// NIR band file
        #[arg(long)]
        nir: PathBuf,
        /// Red band file
        #[arg(long)]
        red: PathBuf,
        /// Output file
        output: PathBuf,
        /// Soil brightness correction factor (0..1)
        #[arg(short, long, default_value = "0.5")]
        l_factor: f64,
    },
    /// EVI: Enhanced Vegetation Index
    Evi {
        /// NIR band file
        #[arg(long)]
        nir: PathBuf,
        /// Red band file
        #[arg(long)]
        red: PathBuf,
        /// Blue band file
        #[arg(long)]
        blue: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// BSI: Bare Soil Index
    Bsi {
        /// SWIR band file
        #[arg(long)]
        swir: PathBuf,
        /// Red band file
        #[arg(long)]
        red: PathBuf,
        /// NIR band file
        #[arg(long)]
        nir: PathBuf,
        /// Blue band file
        #[arg(long)]
        blue: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// Band math: arithmetic between two raster bands
    BandMath {
        /// First input raster
        #[arg(short)]
        a: PathBuf,
        /// Second input raster
        #[arg(short)]
        b: PathBuf,
        /// Output file
        output: PathBuf,
        /// Operation: add, subtract, multiply, divide, power, min, max
        #[arg(long)]
        op: String,
    },
    /// Compute custom spectral index from arithmetic expression
    ///
    /// Common formulas:
    ///   NDVI:  "(NIR - Red) / (NIR + Red)"
    ///   EXG:   "2 * Green - Red - Blue"
    ///   VARI:  "(Green - Red) / (Green + Red - Blue)"
    ///   Clay:  "SWIR1 / SWIR2"
    Calc {
        /// Arithmetic expression using band names
        #[arg(short, long)]
        expression: String,
        /// Band assignments as NAME=path (repeatable)
        #[arg(short, long, value_name = "NAME=FILE")]
        band: Vec<String>,
        /// Output file
        output: PathBuf,
    },
    /// EVI2: Two-band Enhanced Vegetation Index
    Evi2 {
        #[arg(long)]
        nir: PathBuf,
        #[arg(long)]
        red: PathBuf,
        output: PathBuf,
    },
    /// GNDVI: Green Normalized Difference Vegetation Index
    Gndvi {
        #[arg(long)]
        nir: PathBuf,
        #[arg(long)]
        green: PathBuf,
        output: PathBuf,
    },
    /// NGRDI: Normalized Green-Red Difference Index
    Ngrdi {
        #[arg(long)]
        green: PathBuf,
        #[arg(long)]
        red: PathBuf,
        output: PathBuf,
    },
    /// RECI: Red Edge Chlorophyll Index
    Reci {
        #[arg(long)]
        nir: PathBuf,
        #[arg(long)]
        red_edge: PathBuf,
        output: PathBuf,
    },
    /// NDRE: Normalized Difference Red Edge Index
    Ndre {
        #[arg(long)]
        nir: PathBuf,
        #[arg(long)]
        red_edge: PathBuf,
        output: PathBuf,
    },
    /// NDSI: Normalized Difference Snow Index
    Ndsi {
        #[arg(long)]
        green: PathBuf,
        #[arg(long)]
        swir: PathBuf,
        output: PathBuf,
    },
    /// NDMI: Normalized Difference Moisture Index
    Ndmi {
        #[arg(long)]
        nir: PathBuf,
        #[arg(long)]
        swir: PathBuf,
        output: PathBuf,
    },
    /// NDBI: Normalized Difference Built-up Index
    Ndbi {
        #[arg(long)]
        swir: PathBuf,
        #[arg(long)]
        nir: PathBuf,
        output: PathBuf,
    },
    /// MSAVI: Modified Soil-Adjusted Vegetation Index
    Msavi {
        #[arg(long)]
        nir: PathBuf,
        #[arg(long)]
        red: PathBuf,
        output: PathBuf,
    },
    /// Reclassify raster values into discrete classes
    Reclassify {
        input: PathBuf,
        output: PathBuf,
        /// Class definition as "min,max,value" (repeatable)
        #[arg(long, value_name = "MIN,MAX,VALUE")]
        class: Vec<String>,
        /// Default value for unclassified cells
        #[arg(long, default_value = "NaN")]
        default: String,
    },
    /// Per-pixel median composite across multiple rasters
    MedianComposite {
        /// Input raster files (at least 2, repeatable)
        #[arg(short, long)]
        input: Vec<PathBuf>,
        /// Output file
        output: PathBuf,
    },
    /// dNBR: differenced Normalized Burn Ratio (pre/post fire)
    Dnbr {
        #[arg(long)]
        pre_nir: PathBuf,
        #[arg(long)]
        pre_swir: PathBuf,
        #[arg(long)]
        post_nir: PathBuf,
        #[arg(long)]
        post_swir: PathBuf,
        output: PathBuf,
        /// Also output burn severity classification
        #[arg(long)]
        severity_output: Option<PathBuf>,
    },
    /// Cloud mask using Sentinel-2 SCL band
    CloudMask {
        /// Input raster to mask
        input: PathBuf,
        /// SCL classification raster
        #[arg(long)]
        scl: PathBuf,
        /// Output file
        output: PathBuf,
        /// SCL classes to keep (comma-separated, default: 4,5,6,11)
        #[arg(long, default_value = "4,5,6,11")]
        keep: String,
    },
}

// ─── Morphology subcommands ─────────────────────────────────────────────

#[derive(Subcommand)]
pub enum MorphologyCommands {
    /// Erosion (minimum filter)
    Erode {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        /// Structuring element shape: square, cross, disk
        #[arg(long, default_value = "square")]
        shape: String,
        /// Structuring element radius in cells
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Dilation (maximum filter)
    Dilate {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        #[arg(long, default_value = "square")]
        shape: String,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Opening (erosion then dilation) — removes small bright features
    Opening {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        #[arg(long, default_value = "square")]
        shape: String,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Closing (dilation then erosion) — removes small dark features
    Closing {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        #[arg(long, default_value = "square")]
        shape: String,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Morphological gradient (dilation - erosion) — edge detection
    Gradient {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        #[arg(long, default_value = "square")]
        shape: String,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Top-hat transform (original - opening) — bright feature extraction
    TopHat {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        #[arg(long, default_value = "square")]
        shape: String,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Black-hat transform (closing - original) — dark feature extraction
    BlackHat {
        /// Input raster
        input: PathBuf,
        /// Output file
        output: PathBuf,
        #[arg(long, default_value = "square")]
        shape: String,
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
}

// ─── Landscape subcommands ─────────────────────────────────────────────

#[derive(Subcommand)]
pub enum LandscapeCommands {
    /// Label connected patches in a classification raster
    LabelPatches {
        /// Input classification raster (integer class values)
        input: PathBuf,
        /// Output labeled patch raster (i32 IDs)
        output: PathBuf,
        /// Connectivity: 4 (cardinal) or 8 (cardinal+diagonal)
        #[arg(short, long, default_value = "4")]
        connectivity: u8,
    },
    /// Compute per-patch metrics (PARA, FRAC, area, perimeter) as CSV
    PatchMetrics {
        /// Input classification raster
        input: PathBuf,
        /// Output CSV file with per-patch metrics
        #[arg(short, long)]
        output: PathBuf,
        /// Connectivity: 4 or 8
        #[arg(short, long, default_value = "4")]
        connectivity: u8,
    },
    /// Compute per-class metrics (AI, COHESION, proportion)
    ClassMetrics {
        /// Input classification raster
        input: PathBuf,
        /// Connectivity: 4 or 8
        #[arg(short, long, default_value = "4")]
        connectivity: u8,
    },
    /// Compute global landscape metrics (SHDI, SIDI)
    LandscapeMetrics {
        /// Input classification raster
        input: PathBuf,
    },
    /// Full landscape analysis: label + patch metrics + class metrics + landscape metrics
    Analyze {
        /// Input classification raster
        input: PathBuf,
        /// Output labeled raster (optional)
        #[arg(long)]
        output_labels: Option<PathBuf>,
        /// Output CSV with per-patch metrics (optional)
        #[arg(long)]
        output_csv: Option<PathBuf>,
        /// Connectivity: 4 or 8
        #[arg(short, long, default_value = "4")]
        connectivity: u8,
    },
}

// ─── COG subcommands ──────────────────────────────────────────────────

#[cfg(feature = "cloud")]
#[derive(Subcommand)]
pub enum CogCommands {
    /// Show metadata of a remote COG
    Info {
        /// URL of the COG file
        url: String,
    },
    /// Read a bounding box from a remote COG and save to local file
    Fetch {
        /// URL of the COG file
        url: String,
        /// Output GeoTIFF file
        output: PathBuf,
        /// Bounding box: min_x,min_y,max_x,max_y
        #[arg(long)]
        bbox: String,
        /// Overview level (0 = full resolution)
        #[arg(long)]
        overview: Option<usize>,
    },
    /// Calculate slope from a remote COG DEM
    Slope {
        /// URL of the COG DEM
        url: String,
        /// Output file
        output: PathBuf,
        /// Bounding box: min_x,min_y,max_x,max_y
        #[arg(long)]
        bbox: String,
        /// Output units: degrees, percent, radians
        #[arg(short, long, default_value = "degrees")]
        units: String,
        /// Z-factor for unit conversion
        #[arg(short, long, default_value = "1.0")]
        z_factor: f64,
    },
    /// Calculate aspect from a remote COG DEM
    Aspect {
        /// URL of the COG DEM
        url: String,
        /// Output file
        output: PathBuf,
        /// Bounding box: min_x,min_y,max_x,max_y
        #[arg(long)]
        bbox: String,
        /// Output format: degrees, radians, compass
        #[arg(short, long, default_value = "degrees")]
        format: String,
    },
    /// Calculate hillshade from a remote COG DEM
    Hillshade {
        /// URL of the COG DEM
        url: String,
        /// Output file
        output: PathBuf,
        /// Bounding box: min_x,min_y,max_x,max_y
        #[arg(long)]
        bbox: String,
        /// Sun azimuth in degrees (0=North, clockwise)
        #[arg(short, long, default_value = "315")]
        azimuth: f64,
        /// Sun altitude in degrees above horizon
        #[arg(short = 'l', long, default_value = "45")]
        altitude: f64,
        /// Z-factor for vertical exaggeration
        #[arg(short, long, default_value = "1.0")]
        z_factor: f64,
    },
    /// Calculate TPI from a remote COG DEM
    Tpi {
        /// URL of the COG DEM
        url: String,
        /// Output file
        output: PathBuf,
        /// Bounding box: min_x,min_y,max_x,max_y
        #[arg(long)]
        bbox: String,
        /// Neighborhood radius in cells
        #[arg(short, long, default_value = "1")]
        radius: usize,
    },
    /// Fill sinks from a remote COG DEM
    FillSinks {
        /// URL of the COG DEM
        url: String,
        /// Output file
        output: PathBuf,
        /// Bounding box: min_x,min_y,max_x,max_y
        #[arg(long)]
        bbox: String,
        /// Minimum slope to enforce
        #[arg(long, default_value = "0.01")]
        min_slope: f64,
    },
}

// ─── STAC subcommands ────────────────────────────────────────────────

#[cfg(feature = "cloud")]
#[derive(Subcommand)]
pub enum StacCommands {
    /// Search a STAC catalog and list matching items
    Search {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "es")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: Option<String>,
        /// Datetime or range (e.g. "2024-06-01/2024-06-30")
        #[arg(long)]
        datetime: Option<String>,
        /// Collections (comma-separated, e.g. "sentinel-2-l2a")
        #[arg(long)]
        collections: Option<String>,
        /// Maximum items to return
        #[arg(long, default_value = "10")]
        limit: u32,
    },
    /// Search a STAC catalog, fetch the first COG asset, and save to a GeoTIFF
    Fetch {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "es")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: String,
        /// Collection (e.g. "sentinel-2-l2a")
        #[arg(long)]
        collection: String,
        /// Asset key to fetch (e.g. "red", "nir", "B04"). Auto-detects COG if omitted.
        #[arg(long)]
        asset: Option<String>,
        /// Datetime or range
        #[arg(long)]
        datetime: Option<String>,
        /// Variable name for Zarr stores (e.g. "precipitation_amount_1hour_Accumulation")
        #[arg(long)]
        variable: Option<String>,
        /// Time step for Zarr: "first", "last", or ISO datetime (e.g. "2020-06-15")
        #[arg(long, default_value = "first")]
        time_step: String,
        /// Output GeoTIFF file
        output: PathBuf,
    },
    /// Search STAC catalog, fetch ALL matching COG assets, mosaic, and save
    FetchMosaic {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "es")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: String,
        /// Collection (e.g. "cop-dem-glo-30", "sentinel-2-l2a")
        #[arg(long)]
        collection: String,
        /// Asset key to fetch (e.g. "data", "red", "B04"). Auto-detects COG if omitted.
        #[arg(long)]
        asset: Option<String>,
        /// Datetime or range
        #[arg(long)]
        datetime: Option<String>,
        /// Maximum items to fetch and mosaic
        #[arg(long, default_value = "20")]
        max_items: u32,
        /// Output GeoTIFF file
        output: PathBuf,
    },
    /// End-to-end satellite composite: search -> mosaic per date -> cloud-mask -> median composite
    Composite {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "es")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: String,
        /// Collection (e.g. "sentinel-2-l2a")
        #[arg(long)]
        collection: String,
        /// Data asset to composite (e.g. "red", "nir", "B04")
        #[arg(long)]
        asset: String,
        /// Datetime range (e.g. "2024-01-01/2024-12-31")
        #[arg(long)]
        datetime: String,
        /// Maximum number of temporal scenes to composite
        #[arg(long, default_value = "12")]
        max_scenes: usize,
        /// SCL asset key for cloud masking
        #[arg(long, default_value = "scl")]
        scl_asset: String,
        /// SCL classes to keep (comma-separated, default: vegetation,soil,water,snow)
        #[arg(long, default_value = "4,5,6,11")]
        scl_keep: String,
        /// Align output to this raster's grid (resamples to match origin, cell size, dims)
        #[arg(long)]
        align_to: Option<PathBuf>,
        /// Multi-band output naming: "prefix" → {stem}_{band}.tif (default), "asset" → {band}.tif
        #[arg(long, default_value = "prefix")]
        naming: String,
        /// Cache downloaded COG tiles locally (~/.cache/surtgis/cog/) for fast re-runs
        #[arg(long)]
        cache: bool,
        /// Rows per processing strip (larger = fewer HTTP requests but more RAM). Default: 512
        #[arg(long, default_value = "512")]
        strip_rows: usize,
        /// Output GeoTIFF file
        output: PathBuf,
    },
    /// Download a time series: one cloud-free composite per interval (monthly, biweekly, etc.)
    TimeSeries {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "es")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: String,
        /// Collection (e.g. "sentinel-2-l2a")
        #[arg(long)]
        collection: String,
        /// Data asset to download (e.g. "B04", "nir", "red")
        #[arg(long)]
        asset: String,
        /// Full datetime range (e.g. "2020-01-01/2024-12-31")
        #[arg(long)]
        datetime: String,
        /// Temporal interval: "monthly", "biweekly", "weekly", or custom days (e.g. "30")
        #[arg(long, default_value = "monthly")]
        interval: String,
        /// SCL asset key for cloud masking (use "none" to skip)
        #[arg(long, default_value = "scl")]
        scl_asset: String,
        /// Maximum scenes per interval
        #[arg(long, default_value = "8")]
        max_scenes: usize,
        /// Align output to this raster's grid (e.g., a DEM)
        #[arg(long)]
        align_to: Option<PathBuf>,
        /// Output directory (one GeoTIFF per interval)
        output: PathBuf,
    },
    /// Download climate data (Zarr) for a region and time range
    ///
    /// Searches a STAC catalog for climate datasets (ERA5, TerraClimate),
    /// aggregates over time intervals, and writes one GeoTIFF per interval.
    DownloadClimate {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "pc")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: String,
        /// Collection (e.g. "era5-pds")
        #[arg(long)]
        collection: String,
        /// Variable name (e.g. "precipitation_amount_1hour_Accumulation")
        #[arg(long)]
        variable: String,
        /// Datetime range (e.g. "2020-01-01/2020-12-31")
        #[arg(long)]
        datetime: String,
        /// Temporal aggregation: none, daily-sum, daily-mean, monthly-mean, monthly-sum, yearly-mean, yearly-sum
        #[arg(long, default_value = "monthly-mean")]
        aggregate: String,
        /// Output directory (one GeoTIFF per interval)
        output: PathBuf,
    },
    /// List all available STAC catalogs (curated + indexed)
    ListCatalogs {
        /// Search for catalogs by keyword (e.g., "sentinel-2", "dem", "thermal")
        #[arg(long)]
        search: Option<String>,
    },
    /// List collections available in a STAC catalog
    ListCollections {
        /// Catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "pc")]
        catalog: String,
    },
}

// ─── Pipeline workflows ─────────────────────────────────────────────────

#[derive(Subcommand)]
pub enum PipelineCommands {
    /// Compute susceptibility factors from DEM + S2 imagery
    Susceptibility {
        /// DEM source: STAC collection ID (cop-dem-glo-30, cop-dem-glo-90, nasadem, 3dep-seamless) or local file path
        #[arg(long)]
        dem: String,

        /// S2 source: "sentinel-2-l2a" or "earth-search" or "skip"
        #[arg(long)]
        s2: String,

        /// Bounding box: "west,south,east,north"
        #[arg(long)]
        bbox: String,

        /// Date range: "YYYY-MM-DD/YYYY-MM-DD"
        #[arg(long)]
        datetime: String,

        /// Output directory (will be created)
        #[arg(long)]
        outdir: PathBuf,

        /// Max scenes for S2 (default: 12)
        #[arg(long, default_value = "12")]
        max_scenes: usize,

        /// Cloud mask classes to keep for S2 (default: "4,5,6,11")
        #[arg(long, default_value = "4,5,6,11")]
        scl_keep: String,
    },

    /// Generate geomorphometric feature stack from DEM
    #[command(about = "Generate geomorphometric feature stack from DEM")]
    Features {
        /// Input DEM file
        input: PathBuf,
        /// Output directory
        #[arg(short, long)]
        outdir: PathBuf,
        /// Skip hydrology features (faster)
        #[arg(long)]
        skip_hydrology: bool,
        /// Include extra features (valley depth, surface area ratio, landform, wind exposure, accumulation zones)
        #[arg(long)]
        extras: bool,
    },
    /// End-to-end temporal analysis: STAC download → spectral index → trend/stats/phenology
    #[cfg(feature = "cloud")]
    Temporal {
        /// STAC catalog: "pc" (Planetary Computer), "es" (Earth Search), or full URL
        #[arg(long, default_value = "es")]
        catalog: String,
        /// Bounding box: west,south,east,north
        #[arg(long)]
        bbox: String,
        /// Collection (e.g. "sentinel-2-l2a", "landsat-c2-l2")
        #[arg(long)]
        collection: String,
        /// Date range: "YYYY-MM-DD/YYYY-MM-DD"
        #[arg(long)]
        datetime: String,
        /// Temporal interval: "monthly", "biweekly", "weekly", "quarterly", "yearly", or custom days
        #[arg(long, default_value = "monthly")]
        interval: String,
        /// Spectral index to compute: ndvi, ndwi, mndwi, nbr, savi, evi, evi2, bsi, ndbi, ndmi, ndsi, gndvi, ngrdi, ndre, msavi
        #[arg(long)]
        index: String,
        /// Analysis type (comma-separated): stats, trend, phenology
        #[arg(long)]
        analysis: String,
        /// Trend method (when analysis includes "trend"): linear, mann-kendall
        #[arg(long, default_value = "linear")]
        method: String,
        /// Phenology threshold for SOS/EOS (0-1)
        #[arg(long, default_value = "0.5")]
        threshold: f64,
        /// Phenology smoothing window (odd number)
        #[arg(long, default_value = "5")]
        smooth: usize,
        /// Statistics to compute (when analysis includes "stats")
        #[arg(long, default_value = "mean,std,min,max,count")]
        stats: String,
        /// Maximum scenes per interval window
        #[arg(long, default_value = "8")]
        max_scenes: usize,
        /// Output directory
        #[arg(long)]
        outdir: PathBuf,
        /// Keep per-interval index rasters as intermediate outputs
        #[arg(long)]
        keep_intermediates: bool,
        /// Align output to this reference raster's grid (e.g., a DEM)
        #[arg(long)]
        align_to: Option<PathBuf>,
    },
}

// ─── Temporal analysis subcommands ──────────────────────────────────────

#[derive(Subcommand)]
pub enum TemporalCommands {
    /// Per-pixel temporal statistics (mean, std, min, max, count, percentile)
    Stats {
        /// Input rasters (time-ordered GeoTIFFs)
        #[arg(short, long, required = true)]
        input: Vec<PathBuf>,
        /// Output directory for statistic rasters
        #[arg(short, long)]
        outdir: PathBuf,
        /// Which statistics to compute (comma-separated): mean,std,min,max,count,p10,p25,p50,p75,p90
        #[arg(long, default_value = "mean,std,min,max,count")]
        stats: String,
    },
    /// Pixel-wise linear trend analysis (OLS regression)
    Trend {
        /// Input rasters (time-ordered GeoTIFFs)
        #[arg(short, long, required = true)]
        input: Vec<PathBuf>,
        /// Output directory for trend rasters (slope, intercept, r2, pvalue)
        #[arg(short, long)]
        outdir: PathBuf,
        /// Method: "linear" (OLS) or "mann-kendall" (non-parametric)
        #[arg(long, default_value = "linear")]
        method: String,
        /// Time values (comma-separated, e.g. fractional years). If omitted, uses 0,1,2,...
        #[arg(long)]
        times: Option<String>,
    },
    /// Change detection between two dates
    Change {
        /// Before raster (time T1)
        #[arg(long)]
        before: PathBuf,
        /// After raster (time T2)
        #[arg(long)]
        after: PathBuf,
        /// Output difference raster
        output: PathBuf,
        /// Threshold for significant decrease
        #[arg(long, default_value = "-1.0")]
        decrease_threshold: f64,
        /// Threshold for significant increase
        #[arg(long, default_value = "1.0")]
        increase_threshold: f64,
    },
    /// Anomaly detection vs reference period
    Anomaly {
        /// Reference period rasters (baseline, at least 2)
        #[arg(long, required = true)]
        reference: Vec<PathBuf>,
        /// Target rasters to evaluate
        #[arg(long, required = true)]
        target: Vec<PathBuf>,
        /// Output directory
        #[arg(short, long)]
        outdir: PathBuf,
        /// Method: "zscore", "difference", or "percent"
        #[arg(long, default_value = "zscore")]
        method: String,
    },
    /// Vegetation phenology metrics from NDVI/EVI time series
    Phenology {
        /// Input rasters (time-ordered NDVI/EVI GeoTIFFs, at least 6)
        #[arg(short, long, required = true)]
        input: Vec<PathBuf>,
        /// Output directory for phenology rasters (sos, eos, peak, amplitude, etc.)
        #[arg(short, long)]
        outdir: PathBuf,
        /// Day-of-year for each input (comma-separated). If omitted, uses indices.
        #[arg(long)]
        doys: Option<String>,
        /// Threshold for SOS/EOS as fraction of amplitude (0-1)
        #[arg(long, default_value = "0.5")]
        threshold: f64,
        /// Smoothing window size (odd number, 0=none)
        #[arg(long, default_value = "5")]
        smooth: usize,
    },
}

// ─── Vector subcommands ────────────────────────────────────────────────

#[derive(Subcommand)]
pub enum VectorCommands {
    /// Geometric intersection of two vector layers (A ∩ B)
    Intersection {
        /// Input layer A (GeoJSON/Shapefile/GeoPackage)
        input_a: PathBuf,
        /// Input layer B (overlay)
        input_b: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// Geometric union of two vector layers (A ∪ B)
    Union {
        input_a: PathBuf,
        input_b: PathBuf,
        output: PathBuf,
    },
    /// Geometric difference: features of A not covered by B (A - B)
    Difference {
        input_a: PathBuf,
        input_b: PathBuf,
        output: PathBuf,
    },
    /// Symmetric difference: areas in A or B but not both (A ⊕ B)
    SymDifference {
        input_a: PathBuf,
        input_b: PathBuf,
        output: PathBuf,
    },
    /// Dissolve all features into a single geometry
    Dissolve {
        /// Input layer
        input: PathBuf,
        /// Output file
        output: PathBuf,
    },
    /// Buffer features by a distance
    Buffer {
        /// Input layer
        input: PathBuf,
        /// Buffer distance (in CRS units)
        #[arg(long)]
        distance: f64,
        /// Number of segments per quarter circle (default: 8)
        #[arg(long, default_value = "8")]
        segments: usize,
        /// Output file
        output: PathBuf,
    },
}

// ─── Interpolation subcommands ─────────────────────────────────────────

#[derive(Subcommand)]
pub enum InterpolationCommands {
    /// Compute empirical variogram and fit a theoretical model
    Variogram {
        /// Input points (GeoJSON/Shapefile with a numeric attribute)
        points: PathBuf,
        /// Attribute name containing the values to analyze
        #[arg(long)]
        attribute: String,
        /// Number of lag bins (default: 15)
        #[arg(long, default_value = "15")]
        bins: usize,
        /// Maximum lag distance (auto-detect if omitted)
        #[arg(long)]
        max_lag: Option<f64>,
        /// Output JSON file with variogram data and fitted model
        output: PathBuf,
    },
    /// Ordinary Kriging interpolation from points to raster
    Kriging {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid (resolution, extent, CRS)
        #[arg(long)]
        reference: PathBuf,
        /// Variogram model: spherical, exponential, gaussian, matern
        #[arg(long, default_value = "spherical")]
        model: String,
        /// Variogram range (auto-fit if omitted)
        #[arg(long)]
        range: Option<f64>,
        /// Variogram sill (auto-fit if omitted)
        #[arg(long)]
        sill: Option<f64>,
        /// Variogram nugget (default: 0)
        #[arg(long, default_value = "0")]
        nugget: f64,
        /// Maximum neighbors for kriging (default: 16)
        #[arg(long, default_value = "16")]
        max_neighbors: usize,
        /// Output raster
        output: PathBuf,
    },
    /// Universal Kriging with polynomial drift
    UniversalKriging {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Drift order: linear or quadratic
        #[arg(long, default_value = "linear")]
        drift: String,
        /// Variogram model: spherical, exponential, gaussian
        #[arg(long, default_value = "spherical")]
        model: String,
        /// Maximum neighbors (default: 16)
        #[arg(long, default_value = "16")]
        max_neighbors: usize,
        /// Output raster
        output: PathBuf,
    },
    /// Regression-Kriging: ML prediction + kriging on residuals
    RegressionKriging {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with target values
        #[arg(long)]
        attribute: String,
        /// Directory with covariable rasters (features)
        #[arg(long)]
        features: PathBuf,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Variogram model for residuals
        #[arg(long, default_value = "spherical")]
        model: String,
        /// Output raster
        output: PathBuf,
    },
    /// Inverse Distance Weighting interpolation
    Idw {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Power parameter (default: 2.0, higher = more local)
        #[arg(long, default_value = "2.0")]
        power: f64,
        /// Maximum search radius (default: unlimited)
        #[arg(long)]
        max_radius: Option<f64>,
        /// Maximum neighbors (default: all)
        #[arg(long)]
        max_points: Option<usize>,
        /// Output raster
        output: PathBuf,
    },
    /// Nearest Neighbor interpolation (Voronoi/Thiessen)
    NearestNeighbor {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Maximum search radius (default: unlimited)
        #[arg(long)]
        max_radius: Option<f64>,
        /// Output raster
        output: PathBuf,
    },
    /// Natural Neighbor interpolation (Sibson)
    NaturalNeighbor {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Output raster
        output: PathBuf,
    },
    /// Thin Plate Spline interpolation
    Tps {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Smoothing parameter (0 = exact, >0 = smoothing spline)
        #[arg(long, default_value = "0.0")]
        smoothing: f64,
        /// Output raster
        output: PathBuf,
    },
    /// TIN (Triangulated Irregular Network) interpolation
    Tin {
        /// Input points (GeoJSON/Shapefile)
        points: PathBuf,
        /// Attribute name with values
        #[arg(long)]
        attribute: String,
        /// Reference raster for output grid
        #[arg(long)]
        reference: PathBuf,
        /// Output raster
        output: PathBuf,
    },
}

// ─── ML subcommands ────────────────────────────────────────────────────

#[cfg(feature = "ml")]
#[derive(Subcommand)]
pub enum MlCommands {
    /// Extract training samples from feature rasters at point locations
    ExtractSamples {
        /// Directory with features.json and feature rasters (from `pipeline features`)
        #[arg(long)]
        features_dir: PathBuf,
        /// Vector file with labeled points (.geojson, .shp, .gpkg)
        #[arg(long)]
        points: PathBuf,
        /// Property name containing the target label/class
        #[arg(long)]
        target: String,
        /// Output CSV file with extracted samples
        output: PathBuf,
    },
    /// Train a classifier or regressor on a CSV dataset
    Train {
        /// Input CSV file (from extract-samples or external)
        input: PathBuf,
        /// Target column name
        #[arg(long)]
        target: String,
        /// Model type: rf (random-forest), default: rf
        #[arg(long, default_value = "rf")]
        model: String,
        /// Number of estimators (trees)
        #[arg(long, default_value = "100")]
        n_estimators: usize,
        /// Number of cross-validation folds
        #[arg(long, default_value = "5")]
        folds: usize,
        /// Task type: classification or regression
        #[arg(long, default_value = "classification")]
        task: String,
        /// Output model file (.json)
        output: PathBuf,
    },
    /// Predict on rasters using a trained model
    Predict {
        /// Trained model file (.json)
        #[arg(long)]
        model: PathBuf,
        /// Directory with features.json and feature rasters
        #[arg(long)]
        features_dir: PathBuf,
        /// Output prediction raster (.tif)
        output: PathBuf,
    },
    /// Benchmark multiple learners on a dataset
    Benchmark {
        /// Input CSV file
        input: PathBuf,
        /// Target column name
        #[arg(long)]
        target: String,
        /// Number of cross-validation folds
        #[arg(long, default_value = "5")]
        folds: usize,
        /// Task type: classification or regression
        #[arg(long, default_value = "classification")]
        task: String,
    },
}

// ─── Classification subcommands ────────────────────────────────────────

#[derive(Subcommand)]
pub enum ClassificationCommands {
    /// K-means unsupervised clustering
    Kmeans {
        /// Input raster
        input: PathBuf,
        /// Output classified raster
        output: PathBuf,
        /// Number of clusters
        #[arg(short, long, default_value = "5")]
        classes: usize,
        /// Maximum iterations
        #[arg(long, default_value = "100")]
        max_iter: usize,
        /// Convergence threshold
        #[arg(long, default_value = "0.001")]
        convergence: f64,
        /// Random seed
        #[arg(long, default_value = "42")]
        seed: u64,
    },
    /// ISODATA adaptive clustering (auto-splits/merges clusters)
    Isodata {
        /// Input raster
        input: PathBuf,
        /// Output classified raster
        output: PathBuf,
        /// Initial number of clusters
        #[arg(short, long, default_value = "5")]
        classes: usize,
        /// Minimum clusters
        #[arg(long, default_value = "2")]
        min_classes: usize,
        /// Maximum clusters
        #[arg(long, default_value = "10")]
        max_classes: usize,
        /// Maximum iterations
        #[arg(long, default_value = "50")]
        max_iter: usize,
    },
    /// Principal Component Analysis (multi-band input)
    Pca {
        /// Input raster bands (comma-separated paths)
        #[arg(long)]
        bands: String,
        /// Output directory for PC rasters
        output: PathBuf,
        /// Number of components (default: all)
        #[arg(short, long)]
        components: Option<usize>,
    },
    /// Minimum distance supervised classification
    MinDistance {
        /// Input raster
        input: PathBuf,
        /// Output classified raster
        output: PathBuf,
        /// Training raster (class labels)
        #[arg(long)]
        training: PathBuf,
    },
    /// Maximum likelihood supervised classification
    MaxLikelihood {
        /// Input raster
        input: PathBuf,
        /// Output classified raster
        output: PathBuf,
        /// Training raster (class labels)
        #[arg(long)]
        training: PathBuf,
    },
}

// ─── Texture subcommands ───────────────────────────────────────────────

#[derive(Subcommand)]
pub enum TextureCommands {
    /// GLCM texture (Haralick): energy, contrast, homogeneity, correlation, entropy
    Glcm {
        /// Input raster
        input: PathBuf,
        /// Output texture raster
        output: PathBuf,
        /// Texture measure: energy, contrast, homogeneity, correlation, entropy, dissimilarity
        #[arg(short, long, default_value = "contrast")]
        texture: String,
        /// Window radius
        #[arg(short, long, default_value = "3")]
        radius: usize,
        /// Quantization levels
        #[arg(long, default_value = "32")]
        levels: usize,
    },
    /// Sobel edge detection (gradient magnitude)
    Sobel {
        /// Input raster
        input: PathBuf,
        /// Output edge raster
        output: PathBuf,
    },
    /// Laplacian edge detection (second derivative)
    Laplacian {
        /// Input raster
        input: PathBuf,
        /// Output edge raster
        output: PathBuf,
    },
}

// ─── Statistics subcommands ────────────────────────────────────────────

#[derive(Subcommand)]
pub enum StatisticsCommands {
    /// Focal (moving window) statistics
    Focal {
        /// Input raster
        input: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Statistic: mean, std, min, max, range, sum, count, median
        #[arg(short, long, default_value = "mean")]
        stat: String,
        /// Window radius (size = 2r+1)
        #[arg(short, long, default_value = "3")]
        radius: usize,
        /// Use circular window instead of square
        #[arg(long)]
        circular: bool,
    },
    /// Zonal statistics (JSON output by zone)
    Zonal {
        /// Input values raster
        input: PathBuf,
        /// Zone raster (integer classes)
        #[arg(long)]
        zones: PathBuf,
        /// Output JSON file
        output: PathBuf,
    },
    /// Zonal statistics as raster (each cell = zone statistic)
    ZonalRaster {
        /// Input values raster
        input: PathBuf,
        /// Zone raster (integer classes)
        #[arg(long)]
        zones: PathBuf,
        /// Output raster
        output: PathBuf,
        /// Statistic: mean, std, min, max, range, sum, count, median
        #[arg(short, long, default_value = "mean")]
        stat: String,
    },
    /// Global Moran's I spatial autocorrelation (prints result)
    MoransI {
        /// Input raster
        input: PathBuf,
    },
    /// Local Getis-Ord Gi* hotspot analysis
    GetisOrd {
        /// Input raster
        input: PathBuf,
        /// Output z-scores raster
        output: PathBuf,
        /// Neighborhood radius
        #[arg(short, long, default_value = "3")]
        radius: usize,
    },
}