actr-cli 0.3.0

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

const ACTR_SERVICE_TEMPLATE: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/fixtures/swift/ActrService.swift.hbs"
));
const MUTABLE_SCAFFOLD_MARKER: &str = "ACTR: mutable scaffold";
const GENERATED_SCAFFOLD_MARKER: &str = "ACTR: generated scaffold";
const IMPLEMENTED_SCAFFOLD_MARKER: &str = "ACTR: implemented scaffold";
const LEGACY_IMPLEMENTED_MARKER: &str = "ActrService is Implemented";
const LEGACY_UNIMPLEMENTED_MARKERS: [&str; 2] = [
    "ActrService is not implemented",
    "ActrService is not generated",
];
const PROTOBUF_GENERATED_HEADER: &str =
    "Generated by the Swift generator plugin for the protocol buffer compiler.";
const ACTR_FRAMEWORK_GENERATED_HEADER: &str = "Generated by protoc-gen-actrframework-swift";

// Required tools for Swift codegen
const PROTOC: &str = "protoc";
const PROTOC_GEN_SWIFT: &str = "protoc-gen-swift";
const PROTOC_GEN_ACTR_FRAMEWORK_SWIFT: &str = "protoc-gen-actrframework-swift";

pub struct SwiftGenerator;

#[derive(Debug, Clone, PartialEq, Eq)]
struct SwiftTemplateProjectLayout {
    project_root: PathBuf,
    app_root: PathBuf,
    generated_root: PathBuf,
    mutable_scaffold: PathBuf,
}

impl SwiftTemplateProjectLayout {
    fn detect(project_root: &Path, package_name: &str) -> Option<Self> {
        let project_yml = project_root.join("project.yml");
        if !project_yml.exists()
            || !project_root.join("manifest.toml").exists()
            || !project_root.join("manifest.lock.toml").exists()
        {
            return None;
        }

        let project_yml_content = std::fs::read_to_string(&project_yml).ok()?;
        if !project_yml_content.contains("actr-swift") {
            return None;
        }

        let app_root = project_root.join(to_pascal_case(package_name));
        if !app_root.is_dir() {
            return None;
        }

        Some(Self {
            project_root: project_root.to_path_buf(),
            generated_root: app_root.join("Generated"),
            mutable_scaffold: app_root.join("ActrService.swift"),
            app_root,
        })
    }

    fn converge_generated_outputs(&self, generated_files: &[PathBuf]) -> Result<()> {
        for generated_file in generated_files {
            let Some(file_name) = generated_file.file_name() else {
                continue;
            };
            let legacy_file = self.app_root.join(file_name);
            if legacy_file == *generated_file || !legacy_file.exists() {
                continue;
            }

            if self.can_remove_legacy_generated_file(&legacy_file, generated_file)? {
                std::fs::remove_file(&legacy_file).map_err(|e| {
                    ActrCliError::config_error(format!(
                        "Failed to remove legacy generated file {}: {e}",
                        legacy_file.display()
                    ))
                })?;
                info!(
                    "📦 Removed legacy generated Swift file from app root: {}",
                    legacy_file.display()
                );
            } else {
                warn!(
                    "Preserving legacy Swift file at {} because it differs from generated output at {}. Resolve it manually if you no longer want the app-root copy.",
                    legacy_file.display(),
                    generated_file.display()
                );
            }
        }

        Ok(())
    }

    fn can_remove_legacy_generated_file(
        &self,
        legacy_file: &Path,
        generated_file: &Path,
    ) -> Result<bool> {
        let legacy_content = std::fs::read_to_string(legacy_file).map_err(|e| {
            ActrCliError::config_error(format!(
                "Failed to read legacy generated file {}: {e}",
                legacy_file.display()
            ))
        })?;
        let generated_content = std::fs::read_to_string(generated_file).map_err(|e| {
            ActrCliError::config_error(format!(
                "Failed to read generated file {}: {e}",
                generated_file.display()
            ))
        })?;

        if legacy_content == generated_content {
            return Ok(true);
        }

        if !looks_like_generated_swift_source(&legacy_content) {
            return Ok(false);
        }

        Ok(false)
    }
}

#[cfg(target_os = "macos")]
fn colorize_warning_output(output: &str) -> String {
    use owo_colors::OwoColorize;

    let warning_label = format!("{}", "Warning:".yellow());
    output.replace("Warning:", &warning_label)
}

#[async_trait]
impl LanguageGenerator for SwiftGenerator {
    async fn generate_infrastructure(&self, context: &GenContext) -> Result<Vec<PathBuf>> {
        info!("🔧 Generating Swift infrastructure code...");
        let mut generated_files = Vec::new();

        let local_actrframework_plugin = self.ensure_required_tools(context)?;

        // Ensure output directory exists
        std::fs::create_dir_all(&context.output).map_err(|e| {
            ActrCliError::config_error(format!("Failed to create output directory: {e}"))
        })?;

        let proto_root = if context.input_path.is_file() {
            context
                .input_path
                .parent()
                .unwrap_or_else(|| Path::new("."))
        } else {
            context.input_path.as_path()
        };

        // 1. Load manifest.lock.toml if available (it always has actr_type)
        // Try to find manifest.lock.toml by searching up from proto_root
        let lock_file_path = proto_root
            .ancestors()
            .find_map(|p| {
                let lock_path = p.join("manifest.lock.toml");
                if lock_path.exists() {
                    Some(lock_path)
                } else {
                    None
                }
            })
            .unwrap_or_else(|| proto_root.join("manifest.lock.toml"));
        let lock_file = LockFile::from_file(&lock_file_path).ok();
        if lock_file.is_some() {
            debug!("Loaded manifest.lock.toml from: {:?}", lock_file_path);
        } else {
            debug!(
                "manifest.lock.toml not found at: {:?} (will fallback to Config only)",
                lock_file_path
            );
        }

        // 2. Separate local and remote files, and build relative paths
        // Also build a mapping from proto file paths to their actr_type
        let mut remote_paths = Vec::new();
        let mut local_paths = Vec::new();
        let mut remote_file_to_actr_type: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();

        for proto_file in &context.proto_files {
            let is_remote = proto_file.to_string_lossy().contains("/remote/");
            let relative_path = proto_file.strip_prefix(proto_root).unwrap_or(proto_file);
            let path_str = relative_path.to_string_lossy().to_string();

            if is_remote {
                remote_paths.push(path_str.clone());
                // Try to find matching dependency by proto file path
                // Proto file path format: <dependency-alias>/<filename>.proto
                // or remote/<dependency-alias>/<filename>.proto
                if let Some(dep_alias) = relative_path
                    .parent()
                    .and_then(|p| p.file_name())
                    .and_then(|n| n.to_str())
                {
                    debug!(
                        "Trying to match dependency alias: {} for proto file: {}",
                        dep_alias, path_str
                    );

                    // First, try to get actr_type from Config
                    let mut actr_type_str: Option<String> = None;

                    if let Some(dep) = context.config.dependencies.iter().find(|d| {
                        d.alias == dep_alias
                            || d.alias == to_pascal_case(dep_alias)
                            || to_pascal_case(&d.alias) == to_pascal_case(dep_alias)
                    }) {
                        debug!(
                            "Found matching dependency in Config: alias={}, actr_type={:?}",
                            dep.alias, dep.actr_type
                        );
                        if let Some(ref actr_type) = dep.actr_type {
                            // Convert ActrType to canonical string representation.
                            actr_type_str = Some(actr_type.to_string_repr());
                            debug!(
                                "Got actr_type from Config: {}",
                                actr_type_str.as_ref().unwrap()
                            );
                        }
                    }

                    // If not found in Config, try to get from LockFile
                    if actr_type_str.is_none() {
                        if let Some(ref lock) = lock_file {
                            // LockFile uses 'name' field to match (which is the dependency name/alias)
                            if let Some(locked_dep) = lock.get_dependency(dep_alias) {
                                debug!(
                                    "Found matching dependency in LockFile: name={}, actr_type={}",
                                    locked_dep.name, locked_dep.actr_type
                                );
                                actr_type_str = Some(locked_dep.actr_type.clone());
                            } else {
                                debug!(
                                    "No matching dependency found in LockFile for name: {} (available names: {:?})",
                                    dep_alias,
                                    lock.dependencies
                                        .iter()
                                        .map(|d| &d.name)
                                        .collect::<Vec<_>>()
                                );
                            }
                        } else {
                            debug!(
                                "LockFile not found or could not be loaded: {:?}",
                                lock_file_path
                            );
                        }
                    }

                    // If we found an actr_type, add it to the mapping
                    if let Some(actr_type) = actr_type_str {
                        remote_file_to_actr_type.insert(path_str.clone(), actr_type.clone());
                        debug!("Mapped proto file {} to actr_type {}", path_str, actr_type);
                    } else {
                        debug!(
                            "Could not find actr_type for dependency alias: {}",
                            dep_alias
                        );
                    }
                } else {
                    debug!("Could not extract dependency alias from path: {}", path_str);
                }
            } else {
                local_paths.push(path_str);
            }
        }

        // 2. Build the unified options string
        let mut options = format!(
            "Visibility=Public,manufacturer={}",
            context.config.package.actr_type.manufacturer
        );

        if !remote_paths.is_empty() {
            options.push_str(&format!(",RemoteFiles={}", remote_paths.join(":")));
            // Add RemoteFileActrTypes mapping: file1=actr_type1;file2=actr_type2
            if !remote_file_to_actr_type.is_empty() {
                let actr_type_mappings: Vec<String> = remote_file_to_actr_type
                    .iter()
                    .map(|(file, actr_type)| format!("{}={}", file, actr_type))
                    .collect();
                options.push_str(&format!(
                    ",RemoteFileActrTypes={}",
                    actr_type_mappings.join(";")
                ));
            }
        }

        if !local_paths.is_empty() {
            options.push_str(&format!(",LocalFiles={}", local_paths.join(":")));
            // Keep LocalFile for backward compatibility with older plugin versions
            options.push_str(&format!(",LocalFile={}", local_paths[0]));
        }

        // Step 1: Generate basic Swift protobuf types for files that contain messages, enums or extensions
        let swift_proto_files: Vec<_> = context
            .proto_files
            .iter()
            .filter(|p| self.has_messages_enums_or_extensions(p))
            .collect();

        if !swift_proto_files.is_empty() {
            let mut cmd = StdCommand::new("protoc");
            cmd.arg(format!("--proto_path={}", proto_root.display()))
                .arg(format!("--swift_out={}", context.output.display()))
                .arg("--swift_opt=Visibility=Public");

            for proto_file in swift_proto_files {
                cmd.arg(proto_file);
            }

            debug!("Executing protoc (swift): {:?}", cmd);
            let output = cmd.output().map_err(|e| {
                ActrCliError::command_error(format!("Failed to execute protoc (swift): {e}"))
            })?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                return Err(ActrCliError::command_error(format!(
                    "protoc (swift) execution failed: {stderr}"
                )));
            }
        }

        // Step 2: Generate Actor framework code using protoc-gen-actrframework-swift
        // We filter to files that have either services (to generate Actor/Workload)
        // or messages (to generate RpcRequest extensions).
        // For local files, we always include them even if empty to ensure the Workload is generated.
        let actr_proto_files: Vec<_> = context
            .proto_files
            .iter()
            .filter(|p| {
                let is_remote = p.to_string_lossy().contains("/remote/");
                !is_remote || self.has_messages_enums_or_extensions(p) || self.has_services(p)
            })
            .collect();

        if !actr_proto_files.is_empty() {
            let mut cmd = StdCommand::new("protoc");
            cmd.arg(format!("--proto_path={}", proto_root.display()))
                .arg(format!("--actrframework-swift_opt={}", options))
                .arg(format!(
                    "--actrframework-swift_out={}",
                    context.output.display()
                ));
            if let Some(plugin_path) = local_actrframework_plugin.as_ref() {
                cmd.arg(format!(
                    "--plugin=protoc-gen-actrframework-swift={}",
                    plugin_path.display()
                ));
            }

            for proto_file in actr_proto_files {
                cmd.arg(proto_file);
            }

            debug!("Executing protoc (actrframework-swift): {:?}", cmd);
            let output = cmd.output().map_err(|e| {
                ActrCliError::command_error(format!(
                    "Failed to execute protoc (actrframework-swift): {e}"
                ))
            })?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                return Err(ActrCliError::command_error(format!(
                    "protoc (actrframework-swift) execution failed: {stderr}"
                )));
            }
        }

        // Flatten directory structure: move all swift files from subdirectories to output root
        self.flatten_output_directory(&context.output)?;
        // Collect generated files (recursively)
        for entry in walkdir::WalkDir::new(&context.output)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|ext| ext == "swift") {
                generated_files.push(path.to_path_buf());
            }
        }

        if let Some(layout) = self.detect_template_project_layout(context) {
            layout.converge_generated_outputs(&generated_files)?;
        }

        info!("✅ Infrastructure code generation completed");
        Ok(generated_files)
    }

    async fn generate_scaffold(&self, context: &GenContext) -> Result<Vec<PathBuf>> {
        info!("📝 Generating Swift user code scaffold...");
        let mut scaffold_files = Vec::new();

        // 1. Parse local services to get methods for handler implementation
        let mut services = self.parse_local_services(context)?;

        if services.len() > 1 {
            let service_names: Vec<&str> = services.iter().map(|s| s.name.as_str()).collect();
            return Err(ActrCliError::config_error(format!(
                "Multiple services found in local proto files: [{}]. \
                Each ActrNode can only attach a single Workload. \
                Please split each service into its own proto file and project.",
                service_names.join(", ")
            )));
        }

        if let Some(service) = services.first_mut() {
            service.workload_name = self
                .extract_workload_name_for_service(&context.output, &service.name)
                .unwrap_or_else(|| {
                    let fallback = format!("{}Workload", service.name);
                    warn!(
                        "Could not find workload name for service '{}' in generated *.actor.swift files, \
                        falling back to '{}'. Run `actr gen` infrastructure step first.",
                        service.name, fallback
                    );
                    fallback
                });
        }

        // 2. Determine service name for scaffolding
        let service_name = if let Some(service) = services.first() {
            service.name.clone()
        } else if let Some(dep) = context.config.dependencies.first() {
            let type_name = dep
                .actr_type
                .as_ref()
                .map(|t| t.name.clone())
                .or_else(|| dep.service.as_ref().map(|service| service.name.clone()))
                .unwrap_or_else(|| dep.alias.clone());

            debug!("Using service name from dependencies: {}", type_name);
            type_name
        } else {
            // Fallback to the first proto file name
            let guessed_name = context
                .proto_files
                .first()
                .and_then(|f| f.file_stem())
                .and_then(|s| s.to_str())
                .map(to_pascal_case)
                .map(|s| format!("{}Service", s))
                .unwrap_or_else(|| "UnknownService".to_string());

            debug!("Fallback to guessed service name: {}", guessed_name);
            guessed_name
        };

        // Try to read workload name from generated local.actor.swift file
        let workload_name = if let Some(service) = services.first() {
            service.workload_name.clone()
        } else {
            self.extract_first_workload_name_from_generated_file(&context.output)
                .unwrap_or_else(|| {
                    let fallback =
                        format!("{}Workload", to_pascal_case(&context.config.package.name));
                    warn!(
                        "Could not find workload name in generated *.actor.swift files, \
                        falling back to '{}'. Run `actr gen` infrastructure step first.",
                        fallback
                    );
                    fallback
                })
        };

        let scaffold_content = self.generate_scaffold_content(
            &context.config.package.actr_type.manufacturer,
            &service_name,
            &workload_name,
            &services,
        )?;

        let user_file_path = self
            .detect_template_project_layout(context)
            .map(|layout| layout.mutable_scaffold)
            .unwrap_or_else(|| {
                context
                    .output
                    .parent()
                    .unwrap_or_else(|| Path::new("."))
                    .join("ActrService.swift")
            });

        // Check if file exists and should be overwritten
        if user_file_path.exists() {
            let is_scaffold = self.should_overwrite_scaffold(&user_file_path, &scaffold_content)?;

            // Always overwrite scaffold files (generated by init)
            if is_scaffold {
                info!("🔄 Overwriting scaffold file: {:?}", user_file_path);
            } else if !context.overwrite_user_code {
                // Skip non-scaffold files unless overwrite is forced
                info!("⏭️  Skipping existing user code file: {:?}", user_file_path);
                info!("");
                info!("💡 ActrService.swift already exists with user code.");
                info!("   The file was likely created during `actr init` with a template.");
                info!(
                    "   User code scaffold generation is skipped to preserve your implementation."
                );
                info!("   Use --overwrite-user-code flag if you want to regenerate the scaffold.");
                return Ok(scaffold_files);
            } else {
                info!(
                    "🔄 Overwriting existing file (--overwrite-user-code): {:?}",
                    user_file_path
                );
            }
        }

        std::fs::write(&user_file_path, scaffold_content).map_err(|e| {
            ActrCliError::config_error(format!("Failed to write user code scaffold: {e}"))
        })?;

        info!("📄 Generated user code scaffold: {:?}", user_file_path);
        scaffold_files.push(user_file_path);

        info!("✅ User code scaffold generation completed");
        Ok(scaffold_files)
    }

    async fn format_code(&self, _context: &GenContext, _files: &[PathBuf]) -> Result<()> {
        // Swift code formatting is usually done via Xcode or swift-format.
        // For now, we'll skip it as we don't want to enforce a specific tool.
        Ok(())
    }

    async fn validate_code(&self, context: &GenContext) -> Result<()> {
        info!("🔍 Running xcodegen generate...");
        self.ensure_xcodegen_available()?;
        let project_root = self.find_xcodegen_root(context)?;
        let output = StdCommand::new("xcodegen")
            .arg("generate")
            .current_dir(&project_root)
            .output()
            .map_err(|e| ActrCliError::command_error(format!("Failed to run xcodegen: {e}")))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(ActrCliError::command_error(format!(
                "xcodegen generate failed: {stderr}"
            )));
        }

        info!("✅ xcodegen generate completed");
        Ok(())
    }

    fn print_next_steps(&self, context: &GenContext) {
        let project_name = context
            .output
            .parent()
            .and_then(|p| p.file_name())
            .and_then(|s| s.to_str())
            .unwrap_or("YourProject");

        println!("\n🎉 Swift code generation completed!");
        println!("\n📋 Next steps:");
        println!("1. 📖 View immutable generated code: {:?}", context.output);
        if !context.no_scaffold {
            println!("2. ✏️  Implement business logic in ActrService.swift");
            println!("3. 🏗️  xcodegen generate has been run to update your Xcode project");
            println!("4. 🚀 Open {}.xcodeproj and build", project_name);
        } else {
            println!("2. 🏗️  xcodegen generate has been run to update your Xcode project");
            println!("3. 🚀 Open {}.xcodeproj and build", project_name);
        }
        println!("\n💡 Tip: Check the detailed user guide in the generated user code files");
    }
}

impl SwiftGenerator {
    fn ensure_required_tools(&self, context: &GenContext) -> Result<Option<PathBuf>> {
        // 1. Ensure protoc is available.
        let mut missing_tools: Vec<(&str, &str)> = Vec::new();
        if !command_exists(PROTOC) {
            self.try_install_protoc()?;
            if !command_exists(PROTOC) {
                missing_tools.push((PROTOC, "Protocol Buffers compiler"));
            }
        }

        // 2. Try to ensure Swift plugins are available. For these we make a
        //    best-effort attempt to auto-install and only fail if they are
        //    still missing afterwards.
        if !command_exists(PROTOC_GEN_SWIFT) {
            self.try_install_swift_protobuf()?;
            if !command_exists(PROTOC_GEN_SWIFT) {
                missing_tools.push((
                    PROTOC_GEN_SWIFT,
                    "Protocol Buffers Swift codegen plugin (usually provided by swift-protobuf)",
                ));
            }
        }

        let local_actrframework_plugin = self.try_build_workspace_actrframework_swift_plugin()?;

        if local_actrframework_plugin.is_none() && !command_exists(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT)
        {
            self.try_install_actrframework_swift_plugin()?;
            if !command_exists(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT) {
                missing_tools.push((
                    PROTOC_GEN_ACTR_FRAMEWORK_SWIFT,
                    "ActrFramework Swift codegen plugin (protoc-gen-actrframework-swift)",
                ));
            }
        }

        // 3. Check version compatibility for protoc-gen-actrframework-swift
        if local_actrframework_plugin.is_none() && command_exists(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT) {
            self.check_and_update_plugin_version(context)?;
        }

        if missing_tools.is_empty() {
            return Ok(local_actrframework_plugin);
        }

        let mut error_msg = "Missing required tools:\n".to_string();
        for (tool, description) in &missing_tools {
            error_msg.push_str(&format!("  - {tool} ({description})\n"));
        }

        error_msg
            .push_str("\nTried automatic installation for Swift-related tools where possible.\n");
        error_msg.push_str("Please install the missing tools manually and try again.\n\n");
        error_msg.push_str("Suggested installation commands:\n");
        for (tool, _) in &missing_tools {
            match *tool {
                PROTOC => {
                    error_msg.push_str(
                        "  - protoc: install via your package manager, e.g. `brew install protobuf` or `brew reinstall protobuf`\n",
                    );
                }
                PROTOC_GEN_SWIFT => {
                    error_msg.push_str(
                        "  - protoc-gen-swift: install via your package manager, e.g. `brew install swift-protobuf` or `brew reinstall swift-protobuf`; see https://github.com/apple/swift-protobuf\n",
                    );
                }
                PROTOC_GEN_ACTR_FRAMEWORK_SWIFT => {
                    error_msg.push_str(
                        "  - protoc-gen-actrframework-swift: install via your package manager, e.g. `brew install protoc-gen-actrframework-swift` or `brew reinstall protoc-gen-actrframework-swift`\n",
                    );
                }
                _ => {}
            }
        }

        Err(ActrCliError::command_error(error_msg))
    }

    fn try_build_workspace_actrframework_swift_plugin(&self) -> Result<Option<PathBuf>> {
        #[cfg(target_os = "macos")]
        {
            let plugin_root = Path::new(env!("CARGO_MANIFEST_DIR"))
                .parent()
                .map(|path| path.join("tools/protoc-gen/swift"))
                .unwrap_or_else(|| PathBuf::from("tools/protoc-gen/swift"));
            let package_swift = plugin_root.join("Package.swift");
            if !package_swift.is_file() {
                return Ok(None);
            }

            if !command_exists("swift") {
                return Ok(None);
            }

            info!("🔨 Building workspace-local protoc-gen-actrframework-swift...");
            let output = StdCommand::new("swift")
                .args([
                    "build",
                    "-c",
                    "release",
                    "--product",
                    PROTOC_GEN_ACTR_FRAMEWORK_SWIFT,
                    "--arch",
                    "arm64",
                ])
                .current_dir(&plugin_root)
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!(
                        "Failed to build workspace-local {PROTOC_GEN_ACTR_FRAMEWORK_SWIFT}: {e}"
                    ))
                })?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                return Err(ActrCliError::command_error(format!(
                    "workspace-local {PROTOC_GEN_ACTR_FRAMEWORK_SWIFT} build failed: {stderr}"
                )));
            }

            let candidates = [
                plugin_root
                    .join(".build/arm64-apple-macosx/release")
                    .join(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT),
                plugin_root
                    .join(".build/release")
                    .join(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT),
            ];

            for candidate in candidates {
                if candidate.is_file() {
                    info!(
                        "✅ Using workspace-local {} at {}",
                        PROTOC_GEN_ACTR_FRAMEWORK_SWIFT,
                        candidate.display()
                    );
                    return Ok(Some(candidate));
                }
            }

            Err(ActrCliError::command_error(format!(
                "workspace-local {} build completed but binary was not found under {}",
                PROTOC_GEN_ACTR_FRAMEWORK_SWIFT,
                plugin_root.display()
            )))
        }

        #[cfg(not(target_os = "macos"))]
        {
            Ok(None)
        }
    }

    fn should_overwrite_scaffold(&self, path: &Path, expected_scaffold: &str) -> Result<bool> {
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(_) => return Ok(false),
        };

        if content == expected_scaffold {
            return Ok(true);
        }

        // Check for "implemented" marker - if present, never overwrite
        if content.contains(IMPLEMENTED_SCAFFOLD_MARKER)
            || content.contains(LEGACY_IMPLEMENTED_MARKER)
        {
            return Ok(false);
        }

        // New-style scaffold markers are explicit ownership markers.
        // If the content differs from the freshly rendered scaffold, preserve it.
        if content.contains(MUTABLE_SCAFFOLD_MARKER) || content.contains(GENERATED_SCAFFOLD_MARKER)
        {
            return Ok(false);
        }

        let has_legacy_scaffold_marker = LEGACY_UNIMPLEMENTED_MARKERS
            .iter()
            .any(|marker| content.contains(marker));
        if !has_legacy_scaffold_marker {
            return Ok(false);
        }

        // Even if it has scaffold markers, check if it contains substantial user implementation
        // If the file has ActrService class with initialize and shutdown methods,
        // it's likely user code that should be preserved
        let has_actr_service_class =
            content.contains("final class ActrService") || content.contains("class ActrService");
        let has_initialize_method = content.contains("func initialize()");
        let has_shutdown_method = content.contains("func shutdown()");

        // If it has ActrService class with core methods, treat it as user code
        // This covers cases where users have implemented the core functionality
        // even if they haven't removed the scaffold markers
        if has_actr_service_class && has_initialize_method && has_shutdown_method {
            return Ok(false);
        }

        // Only overwrite if it has scaffold markers and appears to be a minimal scaffold
        // (e.g., just the basic structure without substantial implementation)
        Ok(true)
    }

    fn ensure_xcodegen_available(&self) -> Result<()> {
        if command_exists("xcodegen") {
            return Ok(());
        }

        Err(ActrCliError::command_error(
            "xcodegen not found. Install via `brew install xcodegen`.".to_string(),
        ))
    }

    /// Best-effort automatic installation for the Swift Protobuf plugin.
    ///
    /// On macOS with Homebrew available this will run:
    ///   brew install swift-protobuf
    ///
    /// Any failure is logged as a warning and does not immediately error; the
    /// caller is expected to re-check the tool availability and present a
    /// helpful manual-install message if still missing.
    fn try_install_swift_protobuf(&self) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            if !command_exists("brew") {
                debug!("Homebrew not found; skipping automatic swift-protobuf installation");
                return Ok(());
            }

            info!("📦 Installing swift-protobuf via Homebrew (for protoc-gen-swift)...");
            let output = StdCommand::new("brew")
                .arg("install")
                .arg("swift-protobuf")
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!(
                        "Failed to run Homebrew for swift-protobuf installation: {e}"
                    ))
                })?;

            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let combined_output = format!("{stdout}{stderr}");
            if combined_output.contains("Warning:") {
                let highlighted_output = colorize_warning_output(combined_output.trim());
                eprintln!("{highlighted_output}");
            }

            if !output.status.success() {
                warn!(
                    "swift-protobuf installation via Homebrew failed, please install manually.\n{}",
                    stderr
                );
            } else {
                info!("✅ swift-protobuf installation completed");
            }
        }

        #[cfg(not(target_os = "macos"))]
        {
            debug!("Automatic swift-protobuf installation is only supported on macOS (Homebrew)");
        }

        Ok(())
    }

    /// Best-effort automatic installation for protoc.
    ///
    /// On macOS with Homebrew available this will run:
    ///   brew install protobuf
    fn try_install_protoc(&self) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            if !command_exists("brew") {
                debug!("Homebrew not found; skipping automatic protoc installation");
                return Ok(());
            }

            info!("📦 Installing protobuf via Homebrew (for protoc)...");
            let output = StdCommand::new("brew")
                .arg("install")
                .arg("protobuf")
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!(
                        "Failed to run Homebrew for protobuf installation: {e}"
                    ))
                })?;

            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let combined_output = format!("{stdout}{stderr}");
            if combined_output.contains("Warning:") {
                let highlighted_output = colorize_warning_output(combined_output.trim());
                eprintln!("{highlighted_output}");
            }

            if !output.status.success() {
                warn!(
                    "protobuf installation via Homebrew failed, please install manually.\n{}",
                    stderr
                );
            } else {
                info!("✅ protobuf installation completed");
            }
        }

        #[cfg(not(target_os = "macos"))]
        {
            debug!("Automatic protoc installation is only supported on macOS (Homebrew)");
        }

        Ok(())
    }

    /// Best-effort automatic installation hook for protoc-gen-actrframework-swift.
    ///
    /// On macOS with Homebrew available this will run:
    ///   brew install protoc-gen-actrframework-swift
    fn try_install_actrframework_swift_plugin(&self) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            if !command_exists("brew") {
                debug!(
                    "Homebrew not found; skipping Homebrew installation for protoc-gen-actrframework-swift"
                );
                return Ok(());
            }

            info!("📦 Installing protoc-gen-actrframework-swift via Homebrew...");
            let tap_output = StdCommand::new("brew")
                .arg("tap")
                .arg("actor-rtc/homebrew-tap")
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!(
                        "Failed to run Homebrew tap for actor-rtc/homebrew-tap: {e}"
                    ))
                })?;
            if !tap_output.status.success() {
                let stdout = String::from_utf8_lossy(&tap_output.stdout);
                let stderr = String::from_utf8_lossy(&tap_output.stderr);
                warn!(
                    "Homebrew tap for actor-rtc/homebrew-tap failed, please add it manually.\n{}{}",
                    stdout, stderr
                );
            }

            let output = StdCommand::new("brew")
                .arg("install")
                .arg("protoc-gen-actrframework-swift")
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!(
                        "Failed to run Homebrew for protoc-gen-actrframework-swift installation: {e}"
                    ))
                })?;

            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            let combined_output = format!("{stdout}{stderr}");
            if combined_output.contains("Warning:") {
                let highlighted_output = colorize_warning_output(combined_output.trim());
                eprintln!("{highlighted_output}");
            }

            if !output.status.success() {
                warn!(
                    "Homebrew installation for protoc-gen-actrframework-swift failed, please install manually.\n{}",
                    stderr
                );
            } else {
                info!("✅ protoc-gen-actrframework-swift installation completed");
            }
        }

        #[cfg(not(target_os = "macos"))]
        {
            debug!(
                "Automatic installation for protoc-gen-actrframework-swift is only supported on macOS (Homebrew/workspace build)"
            );
        }

        Ok(())
    }

    /// Check installed protoc-gen-actrframework-swift version and ensure it matches actr version
    fn check_and_update_plugin_version(&self, context: &GenContext) -> Result<()> {
        let cli_version = env!("CARGO_PKG_VERSION");
        let min_version =
            self.resolve_plugin_min_version(context, PROTOC_GEN_ACTR_FRAMEWORK_SWIFT)?;
        let plugin_version = self.get_plugin_version()?;

        match (min_version, plugin_version) {
            (Some(min_version), Some(plugin_ver)) => {
                if version_is_at_least(&plugin_ver, &min_version) {
                    debug!(
                        "✅ protoc-gen-actrframework-swift version {} meets minimum version {}",
                        plugin_ver, min_version
                    );
                    return Ok(());
                }

                warn!(
                    "⚠️  protoc-gen-actrframework-swift version {} is lower than minimum version {}",
                    plugin_ver, min_version
                );
                self.try_update_plugin()?;
                let updated_version = self.get_plugin_version()?;
                if let Some(updated_ver) = updated_version {
                    if version_is_at_least(&updated_ver, &min_version) {
                        info!(
                            "✅ Successfully updated protoc-gen-actrframework-swift to version {}",
                            updated_ver
                        );
                        return Ok(());
                    }
                    return Err(ActrCliError::command_error(format!(
                        "protoc-gen-actrframework-swift version {} is still lower than minimum version {} after update. Please manually update it.",
                        updated_ver, min_version
                    )));
                }
                return Err(ActrCliError::command_error(
                    "Failed to get protoc-gen-actrframework-swift version after update".to_string(),
                ));
            }
            (Some(min_version), None) => {
                return Err(ActrCliError::command_error(format!(
                    "Could not determine protoc-gen-actrframework-swift version (minimum required: {}).",
                    min_version
                )));
            }
            (None, Some(plugin_ver)) => match compare_versions(&plugin_ver, cli_version) {
                std::cmp::Ordering::Equal => {
                    debug!(
                        "✅ protoc-gen-actrframework-swift version {} matches actr version {}",
                        plugin_ver, cli_version
                    );
                    return Ok(());
                }
                std::cmp::Ordering::Less => {
                    warn!(
                        "⚠️  protoc-gen-actrframework-swift version {} is lower than actr version {}",
                        plugin_ver, cli_version
                    );
                    self.try_update_plugin()?;
                    let updated_version = self.get_plugin_version()?;
                    if let Some(updated_ver) = updated_version {
                        match compare_versions(&updated_ver, cli_version) {
                            std::cmp::Ordering::Equal => {
                                info!(
                                    "✅ Successfully updated protoc-gen-actrframework-swift to version {}",
                                    updated_ver
                                );
                                return Ok(());
                            }
                            std::cmp::Ordering::Less => {
                                return Err(ActrCliError::command_error(format!(
                                    "protoc-gen-actrframework-swift version {} is still lower than actr version {} after update. Please manually update it.",
                                    updated_ver, cli_version
                                )));
                            }
                            std::cmp::Ordering::Greater => {
                                return Err(ActrCliError::command_error(format!(
                                    "protoc-gen-actrframework-swift version {} is higher than actr version {} after update. Please downgrade actr or upgrade protoc-gen-actrframework-swift.",
                                    updated_ver, cli_version
                                )));
                            }
                        }
                    } else {
                        return Err(ActrCliError::command_error(
                            "Failed to get protoc-gen-actrframework-swift version after update"
                                .to_string(),
                        ));
                    }
                }
                std::cmp::Ordering::Greater => {
                    return Err(ActrCliError::command_error(format!(
                        "protoc-gen-actrframework-swift version {} is higher than actr version {}. Please downgrade protoc-gen-actrframework-swift or upgrade actr.",
                        plugin_ver, cli_version
                    )));
                }
            },
            (None, None) => {
                warn!(
                    "Could not determine protoc-gen-actrframework-swift version, skipping version check"
                );
            }
        }

        Ok(())
    }

    /// Get the version of installed protoc-gen-actrframework-swift
    fn get_plugin_version(&self) -> Result<Option<String>> {
        let output = StdCommand::new(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT)
            .arg("--version")
            .output();

        match output {
            Ok(output) if output.status.success() => {
                let version_info = String::from_utf8_lossy(&output.stdout);
                // Parse version from output, e.g., "protoc-gen-actrframework-swift 0.1.10"
                let version = version_info.lines().next().and_then(|line| {
                    // Try to find version number (e.g., "0.1.10")
                    line.split_whitespace()
                        .find(|s| s.chars().all(|c| c.is_ascii_digit() || c == '.'))
                        .map(|v| v.to_string())
                });

                debug!(
                    "Detected protoc-gen-actrframework-swift version: {:?}",
                    version
                );
                Ok(version)
            }
            _ => {
                debug!("Could not get protoc-gen-actrframework-swift version");
                Ok(None)
            }
        }
    }

    fn resolve_plugin_min_version(
        &self,
        context: &GenContext,
        plugin_name: &str,
    ) -> Result<Option<String>> {
        let config = load_protoc_plugin_config(&context.config_path)?;
        if let Some(config) = config
            && let Some(min_version) = config.min_version(plugin_name)
        {
            info!(
                "🔧 Using minimum version for {} from {}",
                plugin_name,
                config.path().display()
            );
            return Ok(Some(min_version.to_string()));
        }
        Ok(None)
    }

    /// Try to update protoc-gen-actrframework-swift via Homebrew
    fn try_update_plugin(&self) -> Result<()> {
        #[cfg(target_os = "macos")]
        {
            if !command_exists("brew") {
                return Err(ActrCliError::command_error(
                    "Homebrew not found; cannot update protoc-gen-actrframework-swift".to_string(),
                ));
            }

            info!("🔄 Updating Homebrew...");
            let update_output = StdCommand::new("brew")
                .arg("update")
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!("Failed to run brew update: {e}"))
                })?;

            if !update_output.status.success() {
                let stderr = String::from_utf8_lossy(&update_output.stderr);
                warn!("brew update failed: {}", stderr);
            } else {
                info!("✅ Homebrew updated");
            }

            info!("🔄 Reinstalling protoc-gen-actrframework-swift...");
            let reinstall_output = StdCommand::new("brew")
                .arg("reinstall")
                .arg("protoc-gen-actrframework-swift")
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!(
                        "Failed to run brew reinstall protoc-gen-actrframework-swift: {e}"
                    ))
                })?;

            let stdout = String::from_utf8_lossy(&reinstall_output.stdout);
            let stderr = String::from_utf8_lossy(&reinstall_output.stderr);
            let combined_output = format!("{stdout}{stderr}");
            if combined_output.contains("Warning:") {
                let highlighted_output = colorize_warning_output(combined_output.trim());
                eprintln!("{highlighted_output}");
            }

            if !reinstall_output.status.success() {
                return Err(ActrCliError::command_error(format!(
                    "brew reinstall protoc-gen-actrframework-swift failed: {stderr}"
                )));
            }

            info!("✅ protoc-gen-actrframework-swift reinstalled");
        }

        #[cfg(target_os = "macos")]
        {
            Ok(())
        }

        #[cfg(not(target_os = "macos"))]
        {
            Err(ActrCliError::command_error(
                "Automatic update for protoc-gen-actrframework-swift is only supported on macOS (Homebrew)".to_string(),
            ))
        }
    }

    fn has_messages_enums_or_extensions(&self, path: &Path) -> bool {
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => return false,
        };

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty()
                || trimmed.starts_with("//")
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
            {
                continue;
            }
            if trimmed.starts_with("message ")
                || trimmed.starts_with("enum ")
                || trimmed.starts_with("extend ")
            {
                return true;
            }
        }
        false
    }

    fn has_services(&self, path: &Path) -> bool {
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => return false,
        };

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty()
                || trimmed.starts_with("//")
                || trimmed.starts_with("/*")
                || trimmed.starts_with('*')
            {
                continue;
            }
            if trimmed.starts_with("service ") {
                return true;
            }
        }
        false
    }

    /// Flattens the output directory structure by moving all swift files from
    /// subdirectories to the root of the output directory.
    fn flatten_output_directory(&self, output_dir: &Path) -> Result<()> {
        let mut files_to_move = Vec::new();

        // Collect all swift files from subdirectories
        for entry in WalkDir::new(output_dir)
            .min_depth(2) // Skip the root directory itself
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let path = entry.path();
            if path.is_file() && path.extension().is_some_and(|ext| ext == "swift") {
                files_to_move.push(path.to_path_buf());
            }
        }

        // Move each file to the output root, overwriting existing files
        for src_path in files_to_move {
            let file_name = src_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| {
                    ActrCliError::config_error("Failed to get filename from path".to_string())
                })?;

            let mut dst_path = output_dir.to_path_buf();
            dst_path.push(file_name);

            // Overwrite existing files if they are not the same as src_path
            if dst_path.exists() && dst_path != src_path {
                debug!("Overwriting existing file: {:?}", dst_path);
                std::fs::remove_file(&dst_path).map_err(|e| {
                    ActrCliError::config_error(format!(
                        "Failed to remove existing file {:?}: {}",
                        dst_path, e
                    ))
                })?;
            }

            std::fs::rename(&src_path, &dst_path).map_err(|e| {
                ActrCliError::config_error(format!(
                    "Failed to move {} to {}: {}",
                    src_path.display(),
                    dst_path.display(),
                    e
                ))
            })?;
        }

        // Remove empty subdirectories
        self.remove_empty_subdirectories(output_dir)?;

        Ok(())
    }

    /// Recursively removes empty subdirectories from the output directory.
    #[allow(clippy::only_used_in_recursion)]
    fn remove_empty_subdirectories(&self, dir: &Path) -> Result<()> {
        if dir.is_dir() {
            for entry in std::fs::read_dir(dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.is_dir() {
                    self.remove_empty_subdirectories(&path)?;
                    // Only remove if still empty after processing children
                    if path.read_dir()?.next().is_none() {
                        std::fs::remove_dir(&path)?;
                    }
                }
            }
        }
        Ok(())
    }

    fn find_xcodegen_root(&self, context: &GenContext) -> Result<PathBuf> {
        let mut candidates = Vec::new();
        if let Ok(cwd) = std::env::current_dir() {
            candidates.push(cwd);
        }

        candidates.push(context.output.clone());

        if let Some(parent) = context.output.parent() {
            candidates.push(parent.to_path_buf());
            if let Some(grand_parent) = parent.parent() {
                candidates.push(grand_parent.to_path_buf());
            }
        }

        if context.input_path.is_dir() {
            candidates.push(context.input_path.clone());
        } else if let Some(parent) = context.input_path.parent() {
            candidates.push(parent.to_path_buf());
        }

        for candidate in candidates {
            for ancestor in candidate.ancestors() {
                if ancestor.join("project.yml").exists() {
                    return Ok(ancestor.to_path_buf());
                }
            }
        }

        Err(ActrCliError::config_error(
            "project.yml not found; cannot run xcodegen generate",
        ))
    }

    fn detect_template_project_layout(
        &self,
        context: &GenContext,
    ) -> Option<SwiftTemplateProjectLayout> {
        let mut candidates = Vec::new();
        if let Some(parent) = context.output.parent().and_then(|path| path.parent()) {
            candidates.push(parent.to_path_buf());
        }
        if let Ok(project_root) = self.find_xcodegen_root(context) {
            candidates.push(project_root);
        }

        for candidate in candidates {
            if let Some(layout) =
                SwiftTemplateProjectLayout::detect(&candidate, &context.config.package.name)
            {
                return Some(layout);
            }
        }

        None
    }
}

fn looks_like_generated_swift_source(content: &str) -> bool {
    content.contains(PROTOBUF_GENERATED_HEADER) || content.contains(ACTR_FRAMEWORK_GENERATED_HEADER)
}

#[derive(Serialize, Clone)]
struct ProtoService {
    name: String,
    package: String,
    swift_package_prefix: String,
    workload_name: String,
    methods: Vec<ProtoMethod>,
}

#[derive(Serialize, Clone)]
struct ProtoMethod {
    name: String,
    swift_name: String,
    input_type: String,
    output_type: String,
}

impl SwiftGenerator {
    fn parse_local_services(&self, context: &GenContext) -> Result<Vec<ProtoService>> {
        let catalog = ScaffoldCatalog::load(context, SupportedLanguage::Swift)?;

        Ok(catalog
            .local_services
            .into_iter()
            .map(|service| {
                let swift_package_prefix = if service.package.is_empty() {
                    String::new()
                } else {
                    service
                        .package
                        .split('_')
                        .map(|segment| {
                            let mut chars = segment.chars();
                            match chars.next() {
                                None => String::new(),
                                Some(first) => {
                                    first.to_uppercase().collect::<String>() + chars.as_str()
                                }
                            }
                        })
                        .collect::<Vec<_>>()
                        .join("")
                        + "_"
                };

                let methods = service
                    .methods
                    .into_iter()
                    .map(|method| {
                        let mut chars = method.name.chars();
                        let swift_name = match chars.next() {
                            None => String::new(),
                            Some(first) => {
                                first.to_lowercase().collect::<String>() + chars.as_str()
                            }
                        };

                        ProtoMethod {
                            name: method.name,
                            swift_name,
                            input_type: self
                                .swift_type_from_proto(&method.input_type, &swift_package_prefix),
                            output_type: self
                                .swift_type_from_proto(&method.output_type, &swift_package_prefix),
                        }
                    })
                    .collect();

                ProtoService {
                    name: service.name,
                    package: service.package,
                    swift_package_prefix,
                    workload_name: service
                        .workload_type
                        .unwrap_or_else(|| "Workload".to_string()),
                    methods,
                }
            })
            .collect())
    }

    fn extract_actor_name_from_line(&self, line: &str) -> Option<String> {
        let trimmed = line.trim();
        if !trimmed.starts_with("public actor ") || !trimmed.contains(" {") {
            return None;
        }

        let rest = trimmed.trim_start_matches("public actor ").trim_start();
        let actor_name: String = rest
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
            .collect();

        if actor_name.is_empty() {
            None
        } else {
            Some(actor_name)
        }
    }

    /// Extract the first workload name from generated `*.actor.swift` files.
    fn extract_first_workload_name_from_generated_file(&self, output_dir: &Path) -> Option<String> {
        for actor_path in self.generated_actor_files(output_dir) {
            if let Ok(content) = std::fs::read_to_string(&actor_path) {
                for line in content.lines() {
                    if let Some(workload_name) = self.extract_actor_name_from_line(line) {
                        debug!(
                            "Extracted workload name from {}: {}",
                            actor_path.display(),
                            workload_name
                        );
                        return Some(workload_name);
                    }
                }
            }
        }

        None
    }

    /// Extract workload name for a specific service from generated `*.actor.swift` files.
    fn extract_workload_name_for_service(
        &self,
        output_dir: &Path,
        service_name: &str,
    ) -> Option<String> {
        let expected = format!("{}Workload", service_name);

        for actor_path in self.generated_actor_files(output_dir) {
            if let Ok(content) = std::fs::read_to_string(&actor_path) {
                for line in content.lines() {
                    if let Some(actor_name) = self.extract_actor_name_from_line(line) {
                        if actor_name == expected
                            || actor_name
                                .strip_suffix("Workload")
                                .is_some_and(|name| name == service_name)
                        {
                            return Some(actor_name);
                        }
                    }
                }
            }
        }

        None
    }

    fn generated_actor_files(&self, output_dir: &Path) -> Vec<PathBuf> {
        let mut paths: Vec<PathBuf> = WalkDir::new(output_dir)
            .min_depth(1)
            .into_iter()
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.into_path())
            .filter(|path| {
                path.is_file()
                    && path
                        .file_name()
                        .and_then(|name| name.to_str())
                        .is_some_and(|name| name.ends_with(".actor.swift"))
            })
            .collect();
        paths.sort();
        paths
    }

    fn swift_type_from_proto(&self, raw_type: &str, swift_package_prefix: &str) -> String {
        let trimmed = raw_type.trim().trim_start_matches('.');

        // For fully-qualified types (e.g. ".echo_app.EchoRequest" or "other.Foo"),
        // take only the last component — matching framework-codegen-swift's behavior of
        // `method.inputType.split(separator: ".").last!` — then apply the current
        // service's package prefix.
        let type_name = if trimmed.contains('.') {
            trimmed.split('.').next_back().unwrap_or(trimmed)
        } else {
            trimmed
        };

        if swift_package_prefix.is_empty() {
            type_name.to_string()
        } else {
            format!("{}{}", swift_package_prefix, type_name)
        }
    }

    fn generate_scaffold_content(
        &self,
        manufacturer: &str,
        service_name: &str,
        workload_name: &str,
        services: &[ProtoService],
    ) -> Result<String> {
        #[derive(Serialize)]
        struct SwiftScaffoldContext {
            #[serde(rename = "MANUFACTURER")]
            manufacturer: String,
            #[serde(rename = "SERVICE_NAME")]
            service_name: String,
            #[serde(rename = "WORKLOAD_NAME")]
            workload_name: String,
            #[serde(rename = "SERVICES")]
            services: Vec<ProtoService>,
            #[serde(rename = "HAS_SERVICES")]
            has_services: bool,
        }

        let context = SwiftScaffoldContext {
            manufacturer: manufacturer.to_string(),
            service_name: service_name.to_string(),
            workload_name: workload_name.to_string(),
            services: services.to_vec(),
            has_services: !services.is_empty(),
        };

        let mut handlebars = Handlebars::new();
        handlebars.register_escape_fn(handlebars::no_escape);
        Ok(handlebars.render_template(ACTR_SERVICE_TEMPLATE, &context)?)
    }
}

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

    #[test]
    fn generated_scaffold_contains_mutable_marker() {
        let generator = SwiftGenerator;
        let scaffold = generator
            .generate_scaffold_content("demo", "EchoService", "EchoServiceWorkload", &[])
            .expect("render scaffold");

        assert!(scaffold.contains("ACTR: mutable scaffold"));
    }

    #[test]
    fn detects_standard_swift_template_layout() {
        let temp_dir = TempDir::new().unwrap();
        let project_root = temp_dir.path();
        std::fs::write(project_root.join("project.yml"), "actr-swift\n").unwrap();
        std::fs::write(
            project_root.join("manifest.toml"),
            "[package]\nname = \"echo-app\"\n",
        )
        .unwrap();
        std::fs::write(project_root.join("manifest.lock.toml"), "").unwrap();
        std::fs::create_dir_all(project_root.join("EchoApp")).unwrap();

        let layout = SwiftTemplateProjectLayout::detect(project_root, "echo-app")
            .expect("expected standard Swift template layout");

        assert_eq!(layout.app_root, project_root.join("EchoApp"));
        assert_eq!(
            layout.generated_root,
            project_root.join("EchoApp/Generated")
        );
        assert_eq!(
            layout.mutable_scaffold,
            project_root.join("EchoApp/ActrService.swift")
        );
    }

    #[test]
    fn converges_legacy_generated_files_into_generated_directory() {
        let temp_dir = TempDir::new().unwrap();
        let project_root = temp_dir.path();
        let app_root = project_root.join("EchoApp");
        let generated_root = app_root.join("Generated");
        std::fs::create_dir_all(&generated_root).unwrap();
        std::fs::write(project_root.join("project.yml"), "actr-swift\n").unwrap();
        std::fs::write(
            project_root.join("manifest.toml"),
            "[package]\nname = \"echo-app\"\n",
        )
        .unwrap();
        std::fs::write(project_root.join("manifest.lock.toml"), "").unwrap();

        let legacy_file = app_root.join("echo.pb.swift");
        let generated_file = generated_root.join("echo.pb.swift");
        let generated_content =
            "// Generated by the Swift generator plugin for the protocol buffer compiler.\n";
        std::fs::write(&legacy_file, generated_content).unwrap();
        std::fs::write(&generated_file, generated_content).unwrap();

        let layout = SwiftTemplateProjectLayout::detect(project_root, "echo-app")
            .expect("expected standard Swift template layout");
        layout
            .converge_generated_outputs(std::slice::from_ref(&generated_file))
            .expect("converge generated outputs");

        assert!(
            !legacy_file.exists(),
            "legacy generated file should be removed"
        );
        assert!(
            generated_file.exists(),
            "generated file should remain in Generated/"
        );
    }

    #[test]
    fn extracts_first_workload_name_from_service_specific_actor_file() {
        let tmp = TempDir::new().unwrap();
        let output_dir = tmp.path();
        std::fs::write(
            output_dir.join("local_echo.actor.swift"),
            "public actor LocalEchoServiceWorkload<T: LocalEchoServiceHandler> {\n",
        )
        .unwrap();

        let generator = SwiftGenerator;
        let workload = generator.extract_first_workload_name_from_generated_file(output_dir);

        assert_eq!(workload.as_deref(), Some("LocalEchoServiceWorkload"));
    }

    #[test]
    fn extracts_service_workload_name_from_service_specific_actor_file() {
        let tmp = TempDir::new().unwrap();
        let output_dir = tmp.path();
        std::fs::write(
            output_dir.join("local_echo.actor.swift"),
            "public actor LocalEchoServiceWorkload<T: LocalEchoServiceHandler> {\n",
        )
        .unwrap();

        let generator = SwiftGenerator;
        let workload = generator.extract_workload_name_for_service(output_dir, "LocalEchoService");

        assert_eq!(workload.as_deref(), Some("LocalEchoServiceWorkload"));
    }

    #[test]
    fn preserves_modified_legacy_generated_files() {
        let temp_dir = TempDir::new().unwrap();
        let project_root = temp_dir.path();
        let app_root = project_root.join("EchoApp");
        let generated_root = app_root.join("Generated");
        std::fs::create_dir_all(&generated_root).unwrap();
        std::fs::write(project_root.join("project.yml"), "actr-swift\n").unwrap();
        std::fs::write(
            project_root.join("manifest.toml"),
            "[package]\nname = \"echo-app\"\n",
        )
        .unwrap();
        std::fs::write(project_root.join("manifest.lock.toml"), "").unwrap();

        let legacy_file = app_root.join("echo.pb.swift");
        let generated_file = generated_root.join("echo.pb.swift");
        std::fs::write(
            &legacy_file,
            "// Generated by the Swift generator plugin for the protocol buffer compiler.\n// user edit\n",
        )
        .unwrap();
        std::fs::write(
            &generated_file,
            "// Generated by the Swift generator plugin for the protocol buffer compiler.\n",
        )
        .unwrap();

        let layout = SwiftTemplateProjectLayout::detect(project_root, "echo-app")
            .expect("expected standard Swift template layout");
        layout
            .converge_generated_outputs(std::slice::from_ref(&generated_file))
            .expect("converge generated outputs");

        assert!(
            legacy_file.exists(),
            "modified legacy file should be preserved"
        );
        assert!(
            generated_file.exists(),
            "generated file should remain in Generated/"
        );
    }
}