ccgo 3.4.4

A high-performance C++ cross-platform build 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
//! CCGO.toml configuration parsing
//!
//! These structs are parsed from TOML and will be used for native Rust implementation.
//!
//! # Workspace Support
//!
//! CCGO supports workspaces for managing multiple related packages. A workspace is defined
//! by a root CCGO.toml that contains a `[workspace]` section.
//!
//! ## Workspace Configuration Example
//!
//! ```toml
//! [workspace]
//! members = ["core", "utils", "examples/*"]
//! resolver = "2"
//!
//! [workspace.dependencies]
//! fmt = { version = "^10.0", git = "https://github.com/fmtlib/fmt.git" }
//! spdlog = { version = "^1.12" }
//! ```
//!
//! Member packages can inherit workspace dependencies:
//!
//! ```toml
//! [package]
//! name = "my-core"
//! version = "1.0.0"
//!
//! [[dependencies]]
//! name = "fmt"
//! workspace = true
//! ```

#![allow(dead_code)]

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use serde::Deserialize;

/// Root configuration from CCGO.toml
///
/// This can be either a package configuration (with [package] section)
/// or a workspace configuration (with [workspace] section), or both.
///
/// # Simplified Dependencies Syntax
///
/// CCGO supports both array-style and table-style dependency declarations:
///
/// ```toml
/// # Array style (traditional)
/// [[dependencies]]
/// name = "fmt"
/// version = "^10.1"
/// git = "https://github.com/fmtlib/fmt.git"
///
/// # Table style (simplified, requires registry)
/// [dependencies]
/// fmt = "^10.1"
/// spdlog = { version = "1.12.0", features = ["header_only"] }
/// internal-lib = { version = "^2.0", registry = "company" }
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct CcgoConfig {
    /// Package metadata (supports both [package] and [project] sections)
    /// Optional when this is a workspace-only configuration
    #[serde(alias = "project")]
    pub package: Option<PackageConfig>,

    /// Workspace configuration
    pub workspace: Option<WorkspaceConfig>,

    /// Project dependencies (array style: [[dependencies]])
    #[serde(default)]
    pub dependencies: Vec<DependencyConfig>,

    /// Simplified dependencies (table style: [dependencies])
    /// These will be merged with array-style dependencies after parsing
    #[serde(default, rename = "deps")]
    pub simplified_deps: SimplifiedDependencies,

    /// Package registries configuration
    ///
    /// ```toml
    /// [registries]
    /// company = "https://github.com/company/ccgo-packages.git"
    /// private = "git@gitlab.internal:packages/ccgo-index.git"
    /// ```
    #[serde(default)]
    pub registries: RegistriesConfig,

    /// Features configuration
    #[serde(default)]
    pub features: FeaturesConfig,

    /// Build configuration
    pub build: Option<BuildConfig>,

    /// Platform-specific configurations
    pub platforms: Option<PlatformConfigs>,

    /// Binary targets
    #[serde(default, rename = "bin")]
    pub bins: Vec<BinConfig>,

    /// Example programs
    #[serde(default, rename = "example")]
    pub examples: Vec<ExampleConfig>,

    /// Dependency patches configuration
    /// Allows overriding dependency sources for specific crates
    #[serde(default)]
    pub patch: PatchConfig,

    /// Include directory configuration for SDK packaging
    pub include: Option<IncludeConfig>,
}

/// Include directory configuration for SDK packaging.
///
/// ```toml
/// [include]
/// src = "dist/include"   # path relative to project root; defaults to "include"
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct IncludeConfig {
    /// Source directory for include headers (relative to project root).
    /// Defaults to `"include"` when not specified.
    pub src: Option<String>,
}

/// Patch configuration from [patch] section
///
/// Allows overriding dependency sources for specific packages.
/// Similar to Cargo's [patch] feature for dependency override.
///
/// # Example
///
/// ```toml
/// Registries configuration from [registries] section
///
/// Allows configuring custom package registries (Git-based index repositories).
///
/// # Example
///
/// ```toml
/// [registries]
/// company = "https://github.com/company/ccgo-packages.git"
/// private = "git@gitlab.internal:packages/ccgo-index.git"
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct RegistriesConfig {
    /// Registry definitions (name -> URL)
    #[serde(flatten)]
    pub registries: HashMap<String, String>,
}

impl RegistriesConfig {
    /// Check if any registries are configured
    pub fn is_empty(&self) -> bool {
        self.registries.is_empty()
    }

    /// Get a registry URL by name
    pub fn get(&self, name: &str) -> Option<&String> {
        self.registries.get(name)
    }

    /// Iterate over all registries
    pub fn iter(&self) -> impl Iterator<Item = (&String, &String)> {
        self.registries.iter()
    }
}

/// Simplified dependencies from [dependencies] table
///
/// Supports shorthand notation for registry-based dependencies:
///
/// ```toml
/// [dependencies]
/// fmt = "^10.1"                          # version only
/// spdlog = { version = "1.12.0" }        # explicit version
/// json = { version = "^3.11", features = ["ordered"] }
/// internal = { version = "^2.0", registry = "company" }
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SimplifiedDependencies {
    /// Dependencies in table format
    #[serde(flatten)]
    pub deps: HashMap<String, SimplifiedDep>,
}

/// A simplified dependency specification
///
/// Can be either a version string or a table with version and options.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum SimplifiedDep {
    /// Just a version string: `fmt = "^10.1"`
    Version(String),

    /// Full specification with options
    Full(SimplifiedDepSpec),
}

/// Full simplified dependency specification
#[derive(Debug, Clone, Deserialize)]
pub struct SimplifiedDepSpec {
    /// Version requirement
    pub version: String,

    /// Registry name (defaults to "ccgo-packages")
    pub registry: Option<String>,

    /// Features to enable
    #[serde(default)]
    pub features: Vec<String>,

    /// Whether to disable default features
    #[serde(default)]
    pub default_features: Option<bool>,

    /// Whether this dependency is optional
    #[serde(default)]
    pub optional: bool,
}

impl SimplifiedDep {
    /// Get the version requirement
    pub fn version(&self) -> &str {
        match self {
            SimplifiedDep::Version(v) => v,
            SimplifiedDep::Full(spec) => &spec.version,
        }
    }

    /// Get the registry name (None means default)
    pub fn registry(&self) -> Option<&str> {
        match self {
            SimplifiedDep::Version(_) => None,
            SimplifiedDep::Full(spec) => spec.registry.as_deref(),
        }
    }

    /// Get features to enable
    pub fn features(&self) -> &[String] {
        match self {
            SimplifiedDep::Version(_) => &[],
            SimplifiedDep::Full(spec) => &spec.features,
        }
    }

    /// Check if optional
    pub fn is_optional(&self) -> bool {
        match self {
            SimplifiedDep::Version(_) => false,
            SimplifiedDep::Full(spec) => spec.optional,
        }
    }

    /// Convert to DependencyConfig (requires package resolution)
    pub fn to_dependency_config(&self, name: &str) -> DependencyConfig {
        DependencyConfig {
            name: name.to_string(),
            version: self.version().to_string(),
            git: None,
            branch: None,
            path: None,
            zip: None,
            optional: self.is_optional(),
            features: self.features().to_vec(),
            default_features: match self {
                SimplifiedDep::Version(_) => None,
                SimplifiedDep::Full(spec) => spec.default_features,
            },
            workspace: false,
            registry: match self {
                SimplifiedDep::Version(_) => None,
                SimplifiedDep::Full(spec) => spec.registry.clone(),
            },
        }
    }
}

impl SimplifiedDependencies {
    /// Check if there are any simplified dependencies
    pub fn is_empty(&self) -> bool {
        self.deps.is_empty()
    }

    /// Convert all simplified dependencies to DependencyConfig
    pub fn to_dependency_configs(&self) -> Vec<DependencyConfig> {
        self.deps
            .iter()
            .map(|(name, dep)| dep.to_dependency_config(name))
            .collect()
    }
}

/// [patch.crates-io]
/// fmt = { git = "https://github.com/myorg/fmt.git", branch = "custom-fix" }
///
/// [patch."https://github.com/spdlog/spdlog"]
/// spdlog = { path = "../spdlog-local" }
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct PatchConfig {
    /// Patches for registry dependencies (future: when we have package registry)
    #[serde(default, rename = "crates-io")]
    pub crates_io: HashMap<String, PatchDependency>,

    /// Patches for git repositories (keyed by repository URL)
    #[serde(flatten)]
    pub sources: HashMap<String, HashMap<String, PatchDependency>>,
}

/// A patched dependency specification
#[derive(Debug, Clone, Deserialize)]
pub struct PatchDependency {
    /// Git repository URL (alternative source)
    pub git: Option<String>,

    /// Git branch name
    pub branch: Option<String>,

    /// Git tag
    pub tag: Option<String>,

    /// Git revision (commit hash)
    pub rev: Option<String>,

    /// Local path (alternative source)
    pub path: Option<String>,

    /// Version requirement (for verification)
    #[serde(default)]
    pub version: String,
}

impl PatchConfig {
    /// Find a patch for a specific dependency
    ///
    /// Returns the patch specification if a patch is defined for this dependency,
    /// considering both registry patches and source-specific patches.
    pub fn find_patch(&self, dep_name: &str, dep_source: Option<&str>) -> Option<&PatchDependency> {
        // First check source-specific patches if a source is provided
        if let Some(source) = dep_source {
            // Check if we have patches for this specific source
            if let Some(source_patches) = self.sources.get(source) {
                if let Some(patch) = source_patches.get(dep_name) {
                    return Some(patch);
                }
            }
        }

        // Fall back to registry patches (crates-io)
        self.crates_io.get(dep_name)
    }

    /// Check if any patches are defined
    pub fn has_patches(&self) -> bool {
        !self.crates_io.is_empty() || !self.sources.is_empty()
    }

    /// Get all patched dependency names
    pub fn patched_dependencies(&self) -> Vec<&str> {
        let mut deps = Vec::new();

        // Collect from crates-io
        deps.extend(self.crates_io.keys().map(|s| s.as_str()));

        // Collect from source-specific patches
        for source_patches in self.sources.values() {
            deps.extend(source_patches.keys().map(|s| s.as_str()));
        }

        deps.sort();
        deps.dedup();
        deps
    }
}

/// Workspace configuration from [workspace] section
///
/// Workspaces allow managing multiple related packages together with shared
/// dependencies and unified builds.
#[derive(Debug, Clone, Deserialize)]
pub struct WorkspaceConfig {
    /// Workspace member paths (relative to workspace root)
    ///
    /// Supports glob patterns like "examples/*" or "crates/**"
    #[serde(default)]
    pub members: Vec<String>,

    /// Paths to exclude from workspace membership
    ///
    /// Useful when using glob patterns in members
    #[serde(default)]
    pub exclude: Vec<String>,

    /// Dependency resolver version
    ///
    /// - "1": Legacy resolver (default)
    /// - "2": New resolver with better feature unification
    #[serde(default = "default_resolver")]
    pub resolver: String,

    /// Shared dependencies that workspace members can inherit
    #[serde(default)]
    pub dependencies: Vec<WorkspaceDependency>,

    /// Default members for workspace commands
    ///
    /// If not specified, all members are used
    #[serde(default)]
    pub default_members: Vec<String>,
}

fn default_resolver() -> String {
    "1".to_string()
}

impl Default for WorkspaceConfig {
    fn default() -> Self {
        Self {
            members: Vec::new(),
            exclude: Vec::new(),
            resolver: default_resolver(),
            dependencies: Vec::new(),
            default_members: Vec::new(),
        }
    }
}

/// Workspace-level dependency definition
///
/// These dependencies can be inherited by workspace members using `workspace = true`
#[derive(Debug, Clone, Deserialize)]
pub struct WorkspaceDependency {
    /// Dependency name
    pub name: String,

    /// Version requirement
    pub version: String,

    /// Git repository URL
    pub git: Option<String>,

    /// Git branch name
    pub branch: Option<String>,

    /// Git tag
    pub tag: Option<String>,

    /// Git revision (commit hash)
    pub rev: Option<String>,

    /// Local path (for development)
    pub path: Option<String>,

    /// ZIP archive URL or local path (for prebuilt SDK deps)
    pub zip: Option<String>,

    /// Features to enable for this dependency
    #[serde(default)]
    pub features: Vec<String>,

    /// Whether to disable default features for this dependency
    #[serde(default)]
    pub default_features: Option<bool>,
}

impl WorkspaceDependency {
    /// Convert to a regular DependencyConfig
    pub fn to_dependency_config(&self) -> DependencyConfig {
        DependencyConfig {
            name: self.name.clone(),
            version: self.version.clone(),
            git: self.git.clone(),
            branch: self.branch.clone(),
            path: self.path.clone(),
            zip: self.zip.clone(),
            optional: false,
            features: self.features.clone(),
            default_features: self.default_features,
            workspace: false,
            registry: None,
        }
    }
}

/// Package metadata from [package] section
#[derive(Debug, Clone, Deserialize)]
pub struct PackageConfig {
    /// Project name (must be valid C++ identifier)
    pub name: String,

    /// Semver version string
    pub version: String,

    /// Project description
    pub description: Option<String>,

    /// Author list
    pub authors: Option<Vec<String>>,

    /// SPDX license identifier
    pub license: Option<String>,

    /// Git repository URL
    pub repository: Option<String>,
}

/// Binary target configuration from [[bin]] section
///
/// Defines an executable binary target that can be built and run.
///
/// # Example
///
/// ```toml
/// [[bin]]
/// name = "my-cli"
/// path = "src/bin/cli.cpp"
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct BinConfig {
    /// Binary target name (used for executable name)
    pub name: String,

    /// Path to the main source file (relative to project root)
    pub path: String,
}

/// Example configuration from [[example]] section
///
/// Defines an example program that demonstrates library usage.
///
/// # Example
///
/// ```toml
/// [[example]]
/// name = "basic-usage"
/// path = "examples/basic.cpp"  # Optional, defaults to examples/{name}.cpp
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct ExampleConfig {
    /// Example name
    pub name: String,

    /// Path to the example source file (optional)
    /// Defaults to examples/{name}.cpp or examples/{name}/main.cpp
    pub path: Option<String>,
}

/// Dependency configuration from [[dependencies]] array
#[derive(Debug, Clone, Deserialize)]
pub struct DependencyConfig {
    /// Dependency name
    pub name: String,

    /// Version requirement (supports semver ranges like ^1.0, ~1.2.3, >=1.0,<2.0)
    /// Can be empty if `workspace = true` (inherited from workspace)
    #[serde(default)]
    pub version: String,

    /// Git repository URL
    pub git: Option<String>,

    /// Git branch name
    pub branch: Option<String>,

    /// Local path (for development)
    pub path: Option<String>,

    /// ZIP archive URL or local path (for prebuilt SDK deps)
    /// Supports https:// URLs and relative/absolute local paths.
    /// Example: "https://cdn.example.com/foundrycomm_SDK-1.0.0.zip"
    pub zip: Option<String>,

    /// Whether this dependency is optional (only included when a feature enables it)
    #[serde(default)]
    pub optional: bool,

    /// Features to enable for this dependency
    #[serde(default)]
    pub features: Vec<String>,

    /// Whether to disable default features for this dependency
    #[serde(default)]
    pub default_features: Option<bool>,

    /// Whether to inherit this dependency from workspace
    ///
    /// When true, the dependency configuration is inherited from
    /// [workspace.dependencies] in the workspace root CCGO.toml.
    /// Additional features can be specified that will be merged
    /// with the workspace dependency's features.
    #[serde(default)]
    pub workspace: bool,

    /// Registry name (for packages from a specific registry)
    ///
    /// When specified, the package will be resolved from the named registry
    /// instead of the default registry. Registry must be configured in
    /// [registries] section.
    #[serde(default)]
    pub registry: Option<String>,
}

impl DependencyConfig {
    /// Merge with a workspace dependency, inheriting missing fields
    pub fn merge_with_workspace(&mut self, ws_dep: &WorkspaceDependency) {
        // Only merge if workspace inheritance is enabled
        if !self.workspace {
            return;
        }

        // Inherit version if not specified
        if self.version.is_empty() {
            self.version = ws_dep.version.clone();
        }

        // Inherit git if not specified
        if self.git.is_none() {
            self.git = ws_dep.git.clone();
        }

        // Inherit branch if not specified
        if self.branch.is_none() {
            self.branch = ws_dep.branch.clone();
        }

        // Inherit path if not specified
        if self.path.is_none() {
            self.path = ws_dep.path.clone();
        }

        // Merge features (local features are added to workspace features)
        let mut merged_features = ws_dep.features.clone();
        for feat in &self.features {
            if !merged_features.contains(feat) {
                merged_features.push(feat.clone());
            }
        }
        self.features = merged_features;

        // Use workspace default_features if not explicitly set
        if self.default_features.is_none() {
            self.default_features = ws_dep.default_features;
        }
    }
}

/// Features configuration from [features] section
///
/// Features allow conditional compilation and optional dependencies.
/// Similar to Cargo's features system.
///
/// # Example
///
/// ```toml
/// [features]
/// default = ["std"]
/// std = []
/// networking = ["http-client"]
/// advanced = ["networking", "async"]
/// full = ["networking", "advanced", "logging"]
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct FeaturesConfig {
    /// Default features enabled when none are specified
    #[serde(default)]
    pub default: Vec<String>,

    /// Feature definitions - maps feature name to its dependencies
    /// The dependencies can be:
    /// - Other feature names (e.g., "networking")
    /// - Optional dependency names (e.g., "http-client")
    /// - Dependency feature syntax (e.g., "dep-name/feature-name")
    #[serde(flatten)]
    pub features: HashMap<String, Vec<String>>,
}

impl FeaturesConfig {
    /// Check if a feature is defined
    pub fn has_feature(&self, name: &str) -> bool {
        name == "default" || self.features.contains_key(name)
    }

    /// Get all feature names (excluding "default")
    pub fn feature_names(&self) -> Vec<&str> {
        self.features.keys().map(|s| s.as_str()).collect()
    }

    /// Resolve a feature and all its transitive dependencies
    pub fn resolve_feature(&self, name: &str, resolved: &mut HashSet<String>) -> Result<()> {
        // Avoid infinite loops from circular dependencies
        if resolved.contains(name) {
            return Ok(());
        }

        if name == "default" {
            // Resolve all default features
            for default_feature in &self.default {
                self.resolve_feature(default_feature, resolved)?;
            }
            return Ok(());
        }

        // Add this feature to resolved set
        resolved.insert(name.to_string());

        // Get dependencies of this feature
        if let Some(deps) = self.features.get(name) {
            for dep in deps {
                // Check if this is a dependency/feature syntax (e.g., "dep-name/feature")
                if dep.contains('/') {
                    // This is a dependency feature, add as-is for later processing
                    resolved.insert(dep.clone());
                } else if self.has_feature(dep) {
                    // This is another feature, resolve recursively
                    self.resolve_feature(dep, resolved)?;
                } else {
                    // This is likely an optional dependency name
                    resolved.insert(dep.clone());
                }
            }
        }

        Ok(())
    }

    /// Resolve multiple features and return the full set of enabled features
    pub fn resolve_features(&self, requested: &[String], use_defaults: bool) -> Result<HashSet<String>> {
        let mut resolved = HashSet::new();

        // Include default features if requested
        if use_defaults {
            self.resolve_feature("default", &mut resolved)?;
        }

        // Resolve each requested feature
        for feature in requested {
            if !self.has_feature(feature) && !feature.contains('/') {
                bail!("Unknown feature: '{}'. Available features: {:?}",
                    feature, self.feature_names());
            }
            self.resolve_feature(feature, &mut resolved)?;
        }

        Ok(resolved)
    }

    /// Get optional dependencies enabled by a set of resolved features
    pub fn get_enabled_optional_deps<'a>(
        &self,
        resolved_features: &HashSet<String>,
        dependencies: &'a [DependencyConfig],
    ) -> Vec<&'a DependencyConfig> {
        dependencies
            .iter()
            .filter(|dep| {
                if !dep.optional {
                    return true; // Non-optional deps are always included
                }
                // Check if this optional dep is enabled by any feature
                resolved_features.contains(&dep.name)
            })
            .collect()
    }
}

impl DependencyConfig {
    /// Validate the dependency configuration
    pub fn validate(&self) -> Result<()> {
        // Validate version requirement syntax
        crate::version::VersionReq::parse(&self.version)
            .with_context(|| format!("Invalid version requirement '{}' for dependency '{}'", self.version, self.name))?;

        Ok(())
    }
}

/// Build configuration from [build] section
#[derive(Debug, Clone, Deserialize, Default)]
pub struct BuildConfig {
    /// Enable parallel builds
    #[serde(default)]
    pub parallel: bool,

    /// Number of parallel jobs
    pub jobs: Option<usize>,

    /// Symbol visibility (false = hidden, true = default)
    #[serde(default)]
    pub symbol_visibility: bool,

    /// Submodule internal dependencies for shared library linking
    /// Format: { "api" = ["base"], "feature" = ["base", "core"] }
    /// This maps to CCGO_CONFIG_DEPS_MAP CMake variable
    #[serde(default)]
    pub submodule_deps: std::collections::HashMap<String, Vec<String>>,

    /// Relative path (from project root) for the generated `verinfo_gen.h`.
    /// Typically a header directory like `include/stdcomm/base/`.
    ///
    /// When unset, no generation happens at all. When set, also set
    /// `verinfo_source_path` (or let it default) to ensure the generated
    /// `.c` ends up in a directory the project's CMake actually compiles.
    ///
    /// The generated files embed a build identity:
    ///   `<PROJECT>_CCGO_PROJECT_VERIDENTITY=<version>-<ts>-<sha>[-dirty]`
    /// so operators can recover source state via
    /// `strings libfoo.so | grep VERIDENTITY=`.
    pub verinfo_path: Option<String>,

    /// Relative path (from project root) for the generated `verinfo_gen.c`.
    /// Defaults to `src/base/` when unset so it is picked up by ccgo's
    /// default CMake source-glob layout. Override to match project layout,
    /// e.g. `src/stdcomm/base/`.
    pub verinfo_source_path: Option<String>,
}

/// Platform-specific configurations
#[derive(Debug, Clone, Deserialize)]
pub struct PlatformConfigs {
    /// Android configuration
    pub android: Option<AndroidConfig>,

    /// iOS configuration
    pub ios: Option<IosConfig>,

    /// macOS configuration
    pub macos: Option<MacosConfig>,

    /// Windows configuration
    pub windows: Option<WindowsConfig>,

    /// Linux configuration
    pub linux: Option<LinuxConfig>,

    /// OpenHarmony configuration
    pub ohos: Option<OhosConfig>,
}

/// Android platform configuration
#[derive(Debug, Clone, Deserialize)]
pub struct AndroidConfig {
    /// Minimum SDK version
    pub min_sdk: Option<u32>,

    /// Target architectures
    pub architectures: Option<Vec<String>>,
}

/// iOS platform configuration
#[derive(Debug, Clone, Deserialize)]
pub struct IosConfig {
    /// Minimum iOS version
    pub min_version: Option<String>,
}

/// macOS platform configuration
#[derive(Debug, Clone, Deserialize)]
pub struct MacosConfig {
    /// Minimum macOS version
    pub min_version: Option<String>,
}

/// Windows platform configuration
#[derive(Debug, Clone, Deserialize)]
pub struct WindowsConfig {
    /// Toolchain (msvc, mingw, auto)
    pub toolchain: Option<String>,
}

/// Linux platform configuration
#[derive(Debug, Clone, Deserialize)]
pub struct LinuxConfig {
    /// Target architectures
    pub architectures: Option<Vec<String>>,
}

/// OpenHarmony platform configuration
#[derive(Debug, Clone, Deserialize)]
pub struct OhosConfig {
    /// Minimum API version
    pub min_api: Option<u32>,

    /// Target architectures
    pub architectures: Option<Vec<String>>,
}

impl CcgoConfig {
    /// Load configuration from CCGO.toml in current directory
    pub fn load() -> Result<Self> {
        Self::load_from_path("CCGO.toml")
    }

    /// Load configuration from a specific path
    pub fn load_from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read configuration from {}", path.display()))?;

        Self::parse(&content)
    }

    /// Load configuration from a specific file path (alias for compatibility)
    pub fn load_from<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::load_from_path(path)
    }

    /// Parse configuration from TOML string
    pub fn parse(content: &str) -> Result<Self> {
        let mut config: Self = toml::from_str(content).context("Failed to parse CCGO.toml")?;

        // Validate: must have either package or workspace
        if config.package.is_none() && config.workspace.is_none() {
            bail!("CCGO.toml must contain either [package] or [workspace] section");
        }

        // Merge simplified dependencies into the main dependencies list
        // These will need to be resolved via the package registry later
        config.merge_simplified_dependencies();

        // Validate dependencies (only non-workspace dependencies need version validation)
        for dep in &config.dependencies {
            if !dep.workspace {
                dep.validate().with_context(|| format!("Invalid dependency: {}", dep.name))?;
            }
        }

        Ok(config)
    }

    /// Merge simplified dependencies into the main dependencies list
    fn merge_simplified_dependencies(&mut self) {
        if self.simplified_deps.is_empty() {
            return;
        }

        // Convert simplified deps to DependencyConfig
        let simplified_configs = self.simplified_deps.to_dependency_configs();

        // Check for duplicates - collect existing names first
        let existing_names: HashSet<String> = self.dependencies
            .iter()
            .map(|d| d.name.clone())
            .collect();

        for config in simplified_configs {
            if !existing_names.contains(&config.name) {
                self.dependencies.push(config);
            }
        }
    }

    /// Get all registry dependencies (simplified deps that need resolution)
    pub fn registry_dependencies(&self) -> Vec<(&str, &SimplifiedDep)> {
        self.simplified_deps
            .deps
            .iter()
            .map(|(name, dep)| (name.as_str(), dep))
            .collect()
    }

    /// Find CCGO.toml by searching up from current directory
    pub fn find_config() -> Result<PathBuf> {
        let current_dir = std::env::current_dir().context("Failed to get current directory")?;

        let mut dir = current_dir.as_path();
        loop {
            let config_path = dir.join("CCGO.toml");
            if config_path.exists() {
                return Ok(config_path);
            }

            match dir.parent() {
                Some(parent) => dir = parent,
                None => {
                    anyhow::bail!(
                        "Could not find CCGO.toml in current directory or any parent directory"
                    )
                }
            }
        }
    }

    /// Check if this is a workspace configuration
    pub fn is_workspace(&self) -> bool {
        self.workspace.is_some()
    }

    /// Check if this is a package configuration
    pub fn is_package(&self) -> bool {
        self.package.is_some()
    }

    /// Get package configuration, returning an error if not present
    pub fn require_package(&self) -> Result<&PackageConfig> {
        self.package.as_ref().context(
            "This operation requires a [package] section in CCGO.toml.\n\
             Workspace-only configurations cannot be used for this operation."
        )
    }

    /// Get workspace configuration, returning an error if not present
    pub fn require_workspace(&self) -> Result<&WorkspaceConfig> {
        self.workspace.as_ref().context(
            "This operation requires a [workspace] section in CCGO.toml."
        )
    }

    /// Find workspace root by searching up from the given directory
    ///
    /// Returns (workspace_root_path, workspace_config)
    pub fn find_workspace_root(start_dir: &Path) -> Result<Option<(PathBuf, Self)>> {
        let mut dir = start_dir;

        loop {
            let config_path = dir.join("CCGO.toml");
            if config_path.exists() {
                let config = Self::load_from_path(&config_path)?;
                if config.is_workspace() {
                    return Ok(Some((dir.to_path_buf(), config)));
                }
            }

            match dir.parent() {
                Some(parent) => dir = parent,
                None => return Ok(None),
            }
        }
    }

    /// Get workspace member paths
    ///
    /// Resolves glob patterns and returns absolute paths to member directories
    pub fn get_workspace_members(&self, workspace_root: &Path) -> Result<Vec<PathBuf>> {
        let workspace = self.require_workspace()?;
        let mut members = Vec::new();

        for pattern in &workspace.members {
            let full_pattern = workspace_root.join(pattern);
            let pattern_str = full_pattern.to_string_lossy();

            // Use glob to expand patterns
            let paths = glob::glob(&pattern_str)
                .with_context(|| format!("Invalid glob pattern: {}", pattern))?;

            for path_result in paths {
                let path = path_result
                    .with_context(|| format!("Failed to resolve glob pattern: {}", pattern))?;

                // Check if it's a directory with CCGO.toml
                if path.is_dir() && path.join("CCGO.toml").exists() {
                    // Check if excluded
                    let relative = path.strip_prefix(workspace_root)
                        .unwrap_or(&path)
                        .to_string_lossy();

                    let is_excluded = workspace.exclude.iter().any(|exc| {
                        // Simple check - could be improved with proper glob matching
                        relative.starts_with(exc) || relative.as_ref() == exc
                    });

                    if !is_excluded {
                        members.push(path);
                    }
                }
            }
        }

        // Sort for consistent ordering
        members.sort();
        Ok(members)
    }

    /// Load all workspace member configurations
    ///
    /// Returns a list of (member_path, member_config) tuples
    pub fn load_workspace_members(&self, workspace_root: &Path) -> Result<Vec<(PathBuf, Self)>> {
        let member_paths = self.get_workspace_members(workspace_root)?;
        let mut members = Vec::new();

        for member_path in member_paths {
            let config_path = member_path.join("CCGO.toml");
            let config = Self::load_from_path(&config_path)
                .with_context(|| format!("Failed to load member config: {}", config_path.display()))?;
            members.push((member_path, config));
        }

        Ok(members)
    }

    /// Resolve workspace dependencies for this configuration
    ///
    /// If this is a member of a workspace, inherits dependencies marked with `workspace = true`
    /// from the workspace root configuration.
    pub fn resolve_workspace_dependencies(&mut self, workspace_config: &Self) -> Result<()> {
        let workspace = workspace_config.require_workspace()?;

        // Build a map of workspace dependencies for quick lookup
        let ws_deps: HashMap<&str, &WorkspaceDependency> = workspace
            .dependencies
            .iter()
            .map(|d| (d.name.as_str(), d))
            .collect();

        // Resolve each dependency that uses workspace inheritance
        for dep in &mut self.dependencies {
            if dep.workspace {
                if let Some(ws_dep) = ws_deps.get(dep.name.as_str()) {
                    dep.merge_with_workspace(ws_dep);
                } else {
                    bail!(
                        "Dependency '{}' is marked as workspace = true, but not found in \
                         [workspace.dependencies]",
                        dep.name
                    );
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_minimal_config() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"
"#;

        let config = CcgoConfig::parse(toml).unwrap();
        let package = config.package.as_ref().unwrap();
        assert_eq!(package.name, "mylib");
        assert_eq!(package.version, "1.0.0");
    }

    #[test]
    fn test_parse_full_config() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"
description = "My C++ library"
authors = ["Test Author"]
license = "MIT"

[[dependencies]]
name = "fmt"
version = "^10.0"
git = "https://github.com/fmtlib/fmt.git"

[build]
parallel = true
jobs = 4

[platforms.android]
min_sdk = 21
architectures = ["arm64-v8a", "armeabi-v7a"]

[platforms.ios]
min_version = "12.0"
"#;

        let config = CcgoConfig::parse(toml).unwrap();
        let package = config.package.as_ref().unwrap();
        assert_eq!(package.name, "mylib");
        assert_eq!(config.dependencies.len(), 1);
        assert_eq!(config.dependencies[0].name, "fmt");
        assert!(config.build.is_some());
        assert!(config.platforms.is_some());
    }

    #[test]
    fn test_parse_features_config() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[features]
default = ["std"]
std = []
networking = ["http-client"]
advanced = ["networking", "async"]
full = ["networking", "advanced"]

[[dependencies]]
name = "http-client"
version = "^1.0"
optional = true

[[dependencies]]
name = "async"
version = "^2.0"
optional = true
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        // Check features parsed correctly
        assert_eq!(config.features.default, vec!["std"]);
        assert!(config.features.has_feature("std"));
        assert!(config.features.has_feature("networking"));
        assert!(config.features.has_feature("advanced"));
        assert!(config.features.has_feature("full"));

        // Check optional dependencies
        assert_eq!(config.dependencies.len(), 2);
        assert!(config.dependencies[0].optional);
        assert!(config.dependencies[1].optional);
    }

    #[test]
    fn test_features_resolution() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[features]
default = ["std"]
std = []
networking = ["http-client"]
advanced = ["networking"]
full = ["advanced", "logging"]
logging = []
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        // Test resolving single feature
        let resolved = config.features.resolve_features(&["networking".to_string()], false).unwrap();
        assert!(resolved.contains("networking"));
        assert!(resolved.contains("http-client"));
        assert!(!resolved.contains("std")); // No defaults

        // Test resolving with defaults
        let resolved = config.features.resolve_features(&["networking".to_string()], true).unwrap();
        assert!(resolved.contains("networking"));
        assert!(resolved.contains("std")); // Default included

        // Test resolving transitive features
        let resolved = config.features.resolve_features(&["advanced".to_string()], false).unwrap();
        assert!(resolved.contains("advanced"));
        assert!(resolved.contains("networking"));
        assert!(resolved.contains("http-client"));

        // Test resolving complex feature
        let resolved = config.features.resolve_features(&["full".to_string()], false).unwrap();
        assert!(resolved.contains("full"));
        assert!(resolved.contains("advanced"));
        assert!(resolved.contains("networking"));
        assert!(resolved.contains("logging"));
        assert!(resolved.contains("http-client"));
    }

    #[test]
    fn test_features_unknown_feature_error() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[features]
std = []
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        // Requesting unknown feature should error
        let result = config.features.resolve_features(&["unknown".to_string()], false);
        assert!(result.is_err());
    }

    #[test]
    fn test_optional_dependency_filtering() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[features]
networking = ["http-client"]

[[dependencies]]
name = "fmt"
version = "^10.0"

[[dependencies]]
name = "http-client"
version = "^1.0"
optional = true

[[dependencies]]
name = "unused-optional"
version = "^1.0"
optional = true
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        // Without networking feature, only non-optional deps
        let resolved = config.features.resolve_features(&[], false).unwrap();
        let enabled_deps = config.features.get_enabled_optional_deps(&resolved, &config.dependencies);
        assert_eq!(enabled_deps.len(), 1);
        assert_eq!(enabled_deps[0].name, "fmt");

        // With networking feature, http-client should be enabled
        let resolved = config.features.resolve_features(&["networking".to_string()], false).unwrap();
        let enabled_deps = config.features.get_enabled_optional_deps(&resolved, &config.dependencies);
        assert_eq!(enabled_deps.len(), 2);
        let names: Vec<_> = enabled_deps.iter().map(|d| d.name.as_str()).collect();
        assert!(names.contains(&"fmt"));
        assert!(names.contains(&"http-client"));
        assert!(!names.contains(&"unused-optional"));
    }

    #[test]
    fn test_dependency_features() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[[dependencies]]
name = "serde"
version = "^1.0"
features = ["derive", "std"]
default_features = false
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        assert_eq!(config.dependencies[0].features, vec!["derive", "std"]);
        assert_eq!(config.dependencies[0].default_features, Some(false));
    }

    #[test]
    fn test_dependency_feature_syntax() {
        // Test dep/feature syntax in feature dependencies
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[features]
derive = ["serde/derive"]
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        let resolved = config.features.resolve_features(&["derive".to_string()], false).unwrap();
        assert!(resolved.contains("derive"));
        assert!(resolved.contains("serde/derive"));
    }

    #[test]
    fn test_parse_workspace_config() {
        let toml = r#"
[workspace]
members = ["core", "utils", "examples/*"]
exclude = ["examples/deprecated"]
resolver = "2"

[[workspace.dependencies]]
name = "fmt"
version = "^10.0"
git = "https://github.com/fmtlib/fmt.git"

[[workspace.dependencies]]
name = "spdlog"
version = "^1.12"
"#;

        let config = CcgoConfig::parse(toml).unwrap();
        assert!(config.is_workspace());
        assert!(!config.is_package());

        let workspace = config.workspace.as_ref().unwrap();
        assert_eq!(workspace.members, vec!["core", "utils", "examples/*"]);
        assert_eq!(workspace.exclude, vec!["examples/deprecated"]);
        assert_eq!(workspace.resolver, "2");
        assert_eq!(workspace.dependencies.len(), 2);
        assert_eq!(workspace.dependencies[0].name, "fmt");
        assert_eq!(workspace.dependencies[1].name, "spdlog");
    }

    #[test]
    fn test_parse_workspace_with_package() {
        // A CCGO.toml can have both workspace and package sections
        // (virtual workspace root that is also a package)
        let toml = r#"
[workspace]
members = ["crates/*"]

[package]
name = "my-workspace"
version = "1.0.0"
"#;

        let config = CcgoConfig::parse(toml).unwrap();
        assert!(config.is_workspace());
        assert!(config.is_package());

        let package = config.package.as_ref().unwrap();
        assert_eq!(package.name, "my-workspace");
    }

    #[test]
    fn test_workspace_dependency_inheritance() {
        // Workspace config
        let ws_toml = r#"
[workspace]
members = ["core"]

[[workspace.dependencies]]
name = "fmt"
version = "^10.0"
git = "https://github.com/fmtlib/fmt.git"
features = ["std"]
"#;

        // Member config with workspace dependency inheritance
        let member_toml = r#"
[package]
name = "my-core"
version = "1.0.0"

[[dependencies]]
name = "fmt"
workspace = true
features = ["extra"]
"#;

        let ws_config = CcgoConfig::parse(ws_toml).unwrap();
        let mut member_config = CcgoConfig::parse(member_toml).unwrap();

        // Before resolution
        assert!(member_config.dependencies[0].workspace);
        assert!(member_config.dependencies[0].version.is_empty());

        // Resolve workspace dependencies
        member_config.resolve_workspace_dependencies(&ws_config).unwrap();

        // After resolution
        let dep = &member_config.dependencies[0];
        assert_eq!(dep.version, "^10.0");
        assert_eq!(dep.git.as_ref().unwrap(), "https://github.com/fmtlib/fmt.git");
        // Features should be merged (workspace + local)
        assert!(dep.features.contains(&"std".to_string()));
        assert!(dep.features.contains(&"extra".to_string()));
    }

    #[test]
    fn test_workspace_dependency_not_found() {
        let ws_toml = r#"
[workspace]
members = ["core"]

[[workspace.dependencies]]
name = "fmt"
version = "^10.0"
"#;

        let member_toml = r#"
[package]
name = "my-core"
version = "1.0.0"

[[dependencies]]
name = "nonexistent"
workspace = true
"#;

        let ws_config = CcgoConfig::parse(ws_toml).unwrap();
        let mut member_config = CcgoConfig::parse(member_toml).unwrap();

        // Should fail because 'nonexistent' is not in workspace.dependencies
        let result = member_config.resolve_workspace_dependencies(&ws_config);
        assert!(result.is_err());
    }

    #[test]
    fn test_config_requires_package_or_workspace() {
        // Empty config should fail
        let toml = r#"
[build]
parallel = true
"#;

        let result = CcgoConfig::parse(toml);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_patch_config() {
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[[dependencies]]
name = "fmt"
version = "^10.0"
git = "https://github.com/fmtlib/fmt.git"

[patch.crates-io]
fmt = { git = "https://github.com/myorg/fmt.git", branch = "custom-fix" }

[patch."https://github.com/spdlog/spdlog"]
spdlog = { path = "../spdlog-local" }
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        // Check patches parsed correctly
        assert!(config.patch.has_patches());
        assert_eq!(config.patch.patched_dependencies(), vec!["fmt", "spdlog"]);

        // Check crates-io patch
        let fmt_patch = config.patch.find_patch("fmt", None).unwrap();
        assert_eq!(fmt_patch.git.as_ref().unwrap(), "https://github.com/myorg/fmt.git");
        assert_eq!(fmt_patch.branch.as_ref().unwrap(), "custom-fix");

        // Check source-specific patch
        let spdlog_patch = config
            .patch
            .find_patch("spdlog", Some("https://github.com/spdlog/spdlog"))
            .unwrap();
        assert_eq!(spdlog_patch.path.as_ref().unwrap(), "../spdlog-local");
    }

    #[test]
    fn test_patch_priority() {
        // Source-specific patches should take priority over registry patches
        let toml = r#"
[package]
name = "mylib"
version = "1.0.0"

[patch.crates-io]
fmt = { git = "https://github.com/fallback/fmt.git" }

[patch."https://github.com/fmtlib/fmt.git"]
fmt = { path = "../fmt-local" }
"#;

        let config = CcgoConfig::parse(toml).unwrap();

        // When querying with source, should get source-specific patch
        let fmt_with_source = config
            .patch
            .find_patch("fmt", Some("https://github.com/fmtlib/fmt.git"))
            .unwrap();
        assert!(fmt_with_source.path.is_some());

        // When querying without source, should get registry patch
        let fmt_without_source = config.patch.find_patch("fmt", None).unwrap();
        assert!(fmt_without_source.git.is_some());
    }

    #[test]
    fn test_dependency_zip_field() {
        let toml_str = r#"
[package]
name = "myproject"
version = "1.0.0"

[[dependencies]]
name = "foundrycomm"
version = "1.0.0"
zip = "https://cdn.example.com/foundrycomm_SDK-1.0.0.zip"
"#;
        let config: CcgoConfig = toml::from_str(toml_str).unwrap();
        let dep = &config.dependencies[0];
        assert_eq!(dep.name, "foundrycomm");
        assert_eq!(dep.zip.as_deref(), Some("https://cdn.example.com/foundrycomm_SDK-1.0.0.zip"));
        assert!(dep.git.is_none());
        assert!(dep.path.is_none());
    }

    #[test]
    fn test_dependency_zip_field_absent() {
        let toml_str = r#"
[package]
name = "myproject"
version = "1.0.0"

[[dependencies]]
name = "somelib"
version = "1.0.0"
git = "https://github.com/example/somelib.git"
"#;
        let config: CcgoConfig = toml::from_str(toml_str).unwrap();
        let dep = &config.dependencies[0];
        assert!(dep.zip.is_none());
    }
}