actr-cli 0.1.15

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
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"
));

// 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;

#[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();

        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 Actr.lock.toml if available (it always has actr_type)
        // Try to find Actr.lock.toml by searching up from proto_root
        let lock_file_path = proto_root
            .ancestors()
            .find_map(|p| {
                let lock_path = p.join("Actr.lock.toml");
                if lock_path.exists() {
                    Some(lock_path)
                } else {
                    None
                }
            })
            .unwrap_or_else(|| proto_root.join("Actr.lock.toml"));
        let lock_file = LockFile::from_file(&lock_file_path).ok();
        if lock_file.is_some() {
            debug!("Loaded Actr.lock.toml from: {:?}", lock_file_path);
        } else {
            debug!(
                "Actr.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)
                    {
                        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 string representation (manufacturer+name)
                            actr_type_str =
                                Some(format!("{}+{}", actr_type.manufacturer, actr_type.name));
                            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()
                ));

            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());
            }
        }

        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 services = self.parse_local_services(context);

        // 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())
                .unwrap_or_else(|| dep.name.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 = self
            .extract_workload_name_from_generated_file(&context.output)
            .unwrap_or_else(|| {
                // Fallback to generating based on service or package name
                if let Some(service) = services.first() {
                    format!("{}Workload", service.name)
                } else {
                    format!("{}Workload", to_pascal_case(&context.config.package.name))
                }
            });

        let user_file_path = 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)?;

            // 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
                );
            }
        }

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

        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 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<()> {
        // 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)",
                ));
            }
        }

        if !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 command_exists(PROTOC_GEN_ACTR_FRAMEWORK_SWIFT) {
            self.check_and_update_plugin_version(context)?;
        }

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

        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 should_overwrite_scaffold(&self, path: &Path) -> Result<bool> {
        let content = match std::fs::read_to_string(path) {
            Ok(content) => content,
            Err(_) => return Ok(false),
        };

        // Check for "implemented" marker - if present, never overwrite
        if content.contains("ActrService is Implemented") {
            return Ok(false);
        }

        // Check for scaffold markers
        let scaffold_markers = [
            "ActrService is not implemented",
            "ActrService is not generated",
        ];
        let has_scaffold_marker = scaffold_markers
            .iter()
            .any(|marker| content.contains(marker));

        // If no scaffold marker, it's user code - don't overwrite
        if !has_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 actr_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, actr_version) {
                std::cmp::Ordering::Equal => {
                    debug!(
                        "✅ protoc-gen-actrframework-swift version {} matches actr version {}",
                        plugin_ver, actr_version
                    );
                    return Ok(());
                }
                std::cmp::Ordering::Less => {
                    warn!(
                        "⚠️  protoc-gen-actrframework-swift version {} is lower than actr version {}",
                        plugin_ver, actr_version
                    );
                    self.try_update_plugin()?;
                    let updated_version = self.get_plugin_version()?;
                    if let Some(updated_ver) = updated_version {
                        match compare_versions(&updated_ver, actr_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, actr_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, actr_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, actr_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",
        ))
    }
}

#[derive(Serialize, Clone)]
struct ProtoService {
    name: String,
    package: String,
    swift_package_prefix: 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) -> Vec<ProtoService> {
        let mut services = Vec::new();

        for proto_file_path in &context.proto_files {
            // Only look at local files
            if proto_file_path.to_string_lossy().contains("/remote/") {
                continue;
            }

            if let Ok(content) = std::fs::read_to_string(proto_file_path) {
                let mut current_package = String::new();
                let mut current_service: Option<ProtoService> = None;

                for line in content.lines() {
                    let line = line.trim();

                    // Parse package
                    if line.starts_with("package ") {
                        current_package = line
                            .trim_start_matches("package ")
                            .trim_end_matches(';')
                            .trim()
                            .to_string();
                        continue;
                    }

                    // Parse service start
                    if line.starts_with("service ") {
                        let service_name = line
                            .trim_start_matches("service ")
                            .split_whitespace()
                            .next()
                            .unwrap_or("")
                            .trim_end_matches('{')
                            .trim()
                            .to_string();

                        if !service_name.is_empty() {
                            let swift_package_prefix = if current_package.is_empty() {
                                String::new()
                            } else {
                                // Convert echo_app to EchoApp_
                                let parts: Vec<String> = current_package
                                    .split('_')
                                    .map(|s| {
                                        let mut c = s.chars();
                                        match c.next() {
                                            None => String::new(),
                                            Some(f) => {
                                                f.to_uppercase().collect::<String>() + c.as_str()
                                            }
                                        }
                                    })
                                    .collect();
                                parts.join("") + "_"
                            };

                            current_service = Some(ProtoService {
                                name: service_name,
                                package: current_package.clone(),
                                swift_package_prefix,
                                methods: Vec::new(),
                            });
                        }
                        continue;
                    }

                    // Parse rpc method
                    if let Some(ref mut service) = current_service {
                        if line.starts_with("rpc ") {
                            // rpc RelayMessage(RelayMessageRequest) returns (RelayMessageResponse);
                            let line = line.trim_start_matches("rpc ").trim();
                            if let Some(name_end) = line.find('(') {
                                let method_name = line[..name_end].trim().to_string();

                                // swift_name: RelayMessage -> relayMessage
                                let mut chars = method_name.chars();
                                let swift_name = match chars.next() {
                                    None => String::new(),
                                    Some(f) => {
                                        f.to_lowercase().collect::<String>() + chars.as_str()
                                    }
                                };

                                let rest = &line[name_end + 1..];
                                if let Some(input_end) = rest.find(')') {
                                    let input_type = rest[..input_end].trim().to_string();

                                    if let Some(returns_pos) = rest.find("returns") {
                                        let rest = &rest[returns_pos + 7..];
                                        if let Some(output_start) = rest.find('(')
                                            && let Some(output_end) = rest.find(')')
                                        {
                                            let output_type = rest[output_start + 1..output_end]
                                                .trim()
                                                .to_string();

                                            service.methods.push(ProtoMethod {
                                                name: method_name,
                                                swift_name,
                                                input_type: format!(
                                                    "{}{}",
                                                    service.swift_package_prefix, input_type
                                                ),
                                                output_type: format!(
                                                    "{}{}",
                                                    service.swift_package_prefix, output_type
                                                ),
                                            });
                                        }
                                    }
                                }
                            }
                        }

                        if line.contains('}')
                            && let Some(s) = current_service.take()
                        {
                            services.push(s);
                        }
                    }
                }
            }
        }
        services
    }

    /// Extract workload name from generated local.actor.swift file
    fn extract_workload_name_from_generated_file(&self, output_dir: &Path) -> Option<String> {
        let local_actor_path = output_dir.join("local.actor.swift");

        if let Ok(content) = std::fs::read_to_string(&local_actor_path) {
            // Look for pattern: "public actor <WorkloadName> {"
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.starts_with("public actor ") && trimmed.contains(" {") {
                    // Extract the actor name
                    if let Some(start) = trimmed.find("public actor ") {
                        let rest = &trimmed[start + 13..]; // "public actor ".len() = 13
                        if let Some(end) = rest.find(' ') {
                            let workload_name = rest[..end].trim();
                            if !workload_name.is_empty() {
                                debug!(
                                    "Extracted workload name from local.actor.swift: {}",
                                    workload_name
                                );
                                return Some(workload_name.to_string());
                            }
                        }
                    }
                }
            }
        }

        None
    }

    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)?)
    }
}