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
use crate::commands::SupportedLanguage;
use crate::commands::codegen::scaffold::ScaffoldCatalog;
use crate::commands::codegen::traits::{GenContext, LanguageGenerator};
use crate::error::{ActrCliError, Result};
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;

// Template for Python workload scaffold
const ACTR_SERVICE_TEMPLATE: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/fixtures/python/ActrService.py.hbs"
));

// Required tools for Python codegen
const PROTOC: &str = "protoc";
const REQUIRED_TOOLS: &[(&str, &str)] = &[(PROTOC, "Protocol Buffers compiler")];

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

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

pub struct PythonGenerator;

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

        self.ensure_required_tools()?;

        if context.proto_model.local_services.is_empty() {
            return Err(ActrCliError::config_error(
                "Python workload codegen requires at least one local protobuf service. \
                 Client/proxy-only Python codegen is no longer supported because the \
                 legacy Python runtime package was removed."
                    .to_string(),
            ));
        }

        let plugin_path = ensure_python_plugin()?;

        // 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. Read manifest.lock.toml from current working directory
        // The lock file should always be in the project root, not in the protos directory
        let lock_file_path = PathBuf::from("manifest.lock.toml");

        // Check if lock file exists - required for code generation
        if !lock_file_path.exists() {
            return Err(ActrCliError::config_error(format!(
                "manifest.lock.toml not found at {}. Please run 'actr deps install' first.",
                lock_file_path.display()
            )));
        }

        // Read and parse lock file
        let lock_file = LockFile::from_file(&lock_file_path).map_err(|e| {
            ActrCliError::config_error(format!(
                "Failed to read lock file at {}: {}",
                lock_file_path.display(),
                e
            ))
        })?;

        info!("📖 Reading lock file: {}", lock_file_path.display());

        // Build remote services mapping
        let mut remote_services_map: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();

        for dep in lock_file.dependencies {
            for file in dep.files {
                // Map proto file path to actr_type
                // file.path is like "data-stream-peer-concurrent-server-python/data_stream_peer.proto"
                remote_services_map.insert(file.path.clone(), dep.actr_type.clone());
            }
        }

        info!(
            "✅ Found {} remote service mappings",
            remote_services_map.len()
        );

        // 2. Separate local and remote files based on lock file
        // Use a struct to keep path and actr_type paired together
        #[derive(Debug)]
        struct ProtoFileInfo {
            path: String,
            actr_type: Option<String>,
        }

        let mut remote_files = Vec::new();
        let mut local_files = Vec::new();

        for proto_file in &context.proto_files {
            let relative_path = proto_file.strip_prefix(proto_root).unwrap_or(proto_file);

            // Use Path components instead of string matching for reliable path checking
            let components: Vec<_> = relative_path.components().collect();
            let is_remote = components
                .first()
                .and_then(|c| c.as_os_str().to_str())
                .map(|s| s == "remote")
                .unwrap_or(false);

            // Normalize path to use Unix-style separators (cross-platform compatible)
            let path_str = relative_path
                .components()
                .filter_map(|c| c.as_os_str().to_str())
                .collect::<Vec<_>>()
                .join("/");

            if is_remote {
                // Extract path after "remote/" component
                let remote_relative_path = relative_path
                    .components()
                    .skip(1) // Skip the "remote" component
                    .filter_map(|c| c.as_os_str().to_str())
                    .collect::<Vec<_>>()
                    .join("/");

                if remote_relative_path.is_empty() {
                    warn!(
                        "⚠️  Invalid remote path (no content after 'remote/'): {}",
                        path_str
                    );
                    // Treat as local file if path is invalid
                    local_files.push(ProtoFileInfo {
                        path: path_str,
                        actr_type: None,
                    });
                    continue;
                }

                debug!("🔍 Checking remote file: {}", remote_relative_path);

                // Look up actr_type in the lock file mapping
                let actr_type = remote_services_map.get(&remote_relative_path).cloned();

                // Critical: Remote files MUST have actr_type mapping in lock file
                if actr_type.is_none() {
                    return Err(ActrCliError::config_error(format!(
                        "Remote file '{}' not found in lock file.\n\
                         Available remote files in lock:\n  {}\n\n\
                         This usually means:\n\
                         1. The dependency is not listed in manifest.toml\n\
                         2. You need to run 'actr deps install' to update manifest.lock.toml\n\
                         3. The proto file path in the dependency doesn't match",
                        remote_relative_path,
                        remote_services_map
                            .keys()
                            .map(|k| format!("- {}", k))
                            .collect::<Vec<_>>()
                            .join("\n  ")
                    )));
                }

                info!(
                    "✅ Matched remote file '{}' to actr_type '{}'",
                    remote_relative_path,
                    actr_type.as_ref().unwrap()
                );

                remote_files.push(ProtoFileInfo {
                    path: path_str,
                    actr_type,
                });
            } else {
                local_files.push(ProtoFileInfo {
                    path: path_str,
                    actr_type: None,
                });
            }
        }

        // 3. Build the unified options string using key=value format for better reliability

        // Build RemoteFileMapping in format: path1=actr_type1;path2=actr_type2
        let remote_file_mappings: Vec<String> = remote_files
            .iter()
            .filter_map(|f| {
                if let Some(actr_type) = &f.actr_type {
                    Some(format!("{}={}", f.path, actr_type))
                } else {
                    // Log warning for files without actr_type
                    warn!("⚠️  Remote file '{}' has no actr_type mapping", f.path);
                    None
                }
            })
            .collect();

        let local_paths: Vec<String> = local_files.iter().map(|f| f.path.clone()).collect();

        info!("🔍 Remote file mappings: {:?}", remote_file_mappings);
        info!("🔍 Local files: {:?}", local_paths);

        // Build options string
        let mut options = String::new();

        if !remote_file_mappings.is_empty() {
            if !options.is_empty() {
                options.push(',');
            }
            options.push_str(&format!(
                "RemoteFileMapping={}",
                remote_file_mappings.join(";")
            ));
        }

        if !local_paths.is_empty() {
            if !options.is_empty() {
                options.push(',');
            }
            options.push_str(&format!("LocalFiles={}", local_paths.join(":")));
        }

        info!("📝 Options: {}", options);

        // Step 1: Generate basic Python protobuf types for all files at once
        let mut cmd = StdCommand::new("protoc");
        cmd.arg(format!("--proto_path={}", proto_root.display()))
            .arg(format!("--python_out={}", context.output.display()));

        for proto_file in &context.proto_files {
            cmd.arg(proto_file);
        }

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

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

        // Step 2: Generate Actor framework code using protoc-gen-actrpython for all files at once
        let mut cmd = StdCommand::new("protoc");
        cmd.arg(format!("--proto_path={}", proto_root.display()))
            .arg(format!(
                "--plugin=protoc-gen-actrpython={}",
                plugin_path.display()
            ))
            .arg(format!("--actrpython_opt={}", options))
            .arg(format!("--actrpython_out={}", context.output.display()));

        for proto_file in &context.proto_files {
            cmd.arg(proto_file);
        }

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

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

        // Collect generated files (recursively)
        for entry in 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 == "py") {
                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 Python 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() {
            return Err(ActrCliError::config_error(format!(
                "Python workload scaffold requires a local protobuf service; found only dependency '{}'.",
                dep.alias
            )));
        } 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
        };

        let workload_name = "Workload".to_string();
        let filename = "workload.py".to_string();

        let user_file_path = context
            .output
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join(filename);

        // 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);
                return Ok(scaffold_files);
            } else {
                info!(
                    "🔄 Overwriting existing file (--overwrite-user-code): {:?}",
                    user_file_path
                );
            }
        }

        let scaffold_content =
            self.generate_scaffold_content(context, &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<()> {
        // Check if black is available
        if !command_exists("black") {
            info!("💡 black not found, skipping code formatting");
            info!("   Install with: pip3 install black");
            return Ok(());
        }

        info!("🎨 Formatting Python code with black...");

        // Format all Python files in the output directory
        let output = StdCommand::new("black")
            .arg("--quiet")
            .arg(&context.output)
            .output()
            .map_err(|e| ActrCliError::command_error(format!("Failed to run black: {e}")))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            warn!("⚠️  Black formatting encountered issues: {}", stderr);
            // Don't fail on formatting errors, just warn
            return Ok(());
        }

        // Also format scaffold file if it exists and is in the files list
        for file in files {
            if file.exists() && file.extension().is_some_and(|ext| ext == "py") {
                let output = StdCommand::new("black")
                    .arg("--quiet")
                    .arg(file)
                    .output()
                    .map_err(|e| {
                        ActrCliError::command_error(format!(
                            "Failed to run black on {:?}: {e}",
                            file
                        ))
                    })?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    warn!("⚠️  Black formatting failed for {:?}: {}", file, stderr);
                }
            }
        }

        info!("✅ Code formatting completed");
        Ok(())
    }

    async fn validate_code(&self, context: &GenContext) -> Result<()> {
        info!("🔍 Validating Python code...");

        // Check if python3 is available
        if !command_exists("python3") && !command_exists("python") {
            warn!("⚠️  Python not found, skipping code validation");
            return Ok(());
        }

        let python_cmd = if command_exists("python3") {
            "python3"
        } else {
            "python"
        };

        // Check protobuf version
        check_python_protobuf_version(python_cmd)?;

        // Collect all Python files in the output directory
        let mut python_files = Vec::new();
        for entry in 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 == "py") {
                python_files.push(path.to_path_buf());
            }
        }

        if python_files.is_empty() {
            info!("💡 No Python files found to validate");
            return Ok(());
        }

        info!("🔍 Validating {} Python files...", python_files.len());

        // Validate each file using py_compile
        let mut failed_files = Vec::new();
        for file in &python_files {
            let output = StdCommand::new(python_cmd)
                .arg("-m")
                .arg("py_compile")
                .arg(file)
                .output()
                .map_err(|e| {
                    ActrCliError::command_error(format!("Failed to run python -m py_compile: {e}"))
                })?;

            if !output.status.success() {
                let stderr = String::from_utf8_lossy(&output.stderr);
                warn!("⚠️  Syntax error in {:?}: {}", file, stderr);
                failed_files.push((file.clone(), stderr.to_string()));
            }
        }

        if !failed_files.is_empty() {
            let mut error_msg = format!(
                "Python syntax validation failed for {} files:\n",
                failed_files.len()
            );
            for (file, error) in failed_files {
                error_msg.push_str(&format!("  - {:?}: {}\n", file, error));
            }
            return Err(ActrCliError::command_error(error_msg));
        }

        info!("✅ Python code validation completed successfully");
        Ok(())
    }

    fn print_next_steps(&self, context: &GenContext) {
        println!("\n🎉 Python code generation completed!");
        println!("\n📋 Next steps:");
        println!("1. 📖 View generated code: {:?}", context.output);
        println!("2. 🐍 Edit workload.py and implement the generated handler methods");
        println!("3. 📦 Run ./build.sh package to componentize and package the workload");
        println!("\n💡 Tip: Use a virtual environment for componentize-py dependencies");
    }
}

impl PythonGenerator {
    fn ensure_required_tools(&self) -> Result<()> {
        let mut missing_tools = Vec::new();
        for (tool, description) in REQUIRED_TOOLS {
            if !command_exists(tool) {
                missing_tools.push((tool, description));
            }
        }

        if !missing_tools.is_empty() {
            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("\nPlease install the missing tools and try again.");
            return Err(ActrCliError::command_error(error_msg));
        }

        Ok(())
    }

    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 if file contains scaffold markers
        let markers = [
            "# DO NOT EDIT - Generated scaffold",
            "TODO: Implement your business logic",
            "is not implemented yet",
        ];

        Ok(markers.iter().any(|marker| content.contains(marker)))
    }

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

        Ok(catalog
            .local_services
            .into_iter()
            .map(|service| ProtoService {
                name: service.name.clone(),
                package: service.package.clone(),
                proto_module: proto_module_from_path(&service.proto_file),
                pb2_package: pb2_package_from_path(&service.proto_file),
                generated_module: generated_workload_module(&service.package, &service.name),
                methods: service
                    .methods
                    .into_iter()
                    .map(|method| ProtoMethod {
                        name: method.name,
                        snake_name: method.snake_name,
                        input_type: method.input_type,
                        output_type: method.output_type,
                        route_key: method.route_key,
                    })
                    .collect(),
            })
            .collect())
    }

    fn generate_scaffold_content(
        &self,
        _context: &GenContext,
        service_name: &str,
        workload_name: &str,
        services: &[ProtoService],
    ) -> Result<String> {
        #[derive(Serialize)]
        struct ScaffoldContext {
            #[serde(rename = "SERVICE_NAME")]
            service_name: String,
            #[serde(rename = "WORKLOAD_NAME")]
            workload_name: String,
            #[serde(rename = "DISPATCHER_NAME")]
            dispatcher_name: String,
            #[serde(rename = "PROTO_MODULE")]
            proto_module: String,
            #[serde(rename = "PB2_MODULE")]
            pb2_module: String,
            #[serde(rename = "ACTOR_MODULE")]
            actor_module: String,
            #[serde(rename = "SERVICES")]
            services: Vec<ProtoService>,
            #[serde(rename = "HAS_SERVICES")]
            has_services: bool,
        }

        let first_service = services.first().ok_or_else(|| {
            ActrCliError::config_error(
                "Python workload scaffold requires at least one local service".to_string(),
            )
        })?;

        let proto_module = first_service.proto_module.clone();
        let pb2_module = first_service.pb2_package.clone();
        let actor_module = first_service.generated_module.clone();

        let dispatcher_name = services
            .first()
            .map(|s| format!("{}Dispatcher", s.name))
            .unwrap_or_else(|| "Dispatcher".to_string());

        let context = ScaffoldContext {
            service_name: service_name.to_string(),
            workload_name: workload_name.to_string(),
            dispatcher_name,
            proto_module,
            pb2_module,
            actor_module,
            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)?)
    }
}

fn proto_module_from_path(path: &Path) -> String {
    path.file_stem()
        .and_then(|stem| stem.to_str())
        .unwrap_or("proto")
        .to_string()
}

fn pb2_package_from_path(path: &Path) -> String {
    let mut parts = vec!["generated".to_string()];
    if let Some(parent) = path.parent() {
        for component in parent.components() {
            if let Some(value) = component.as_os_str().to_str()
                && !value.is_empty()
                && value != "."
            {
                parts.push(value.replace('-', "_"));
            }
        }
    }
    parts.join(".")
}

fn generated_workload_module(package: &str, service_name: &str) -> String {
    let base = if package.is_empty() {
        to_snake_case(service_name)
    } else {
        package.replace(['.', '-'], "_").to_ascii_lowercase()
    };
    format!("{base}_workload")
}

// Helper function to convert CamelCase to snake_case
fn to_snake_case(name: &str) -> String {
    let mut result = String::new();
    for (i, ch) in name.chars().enumerate() {
        if ch.is_uppercase() && i != 0 {
            result.push('_');
        }
        result.push(ch.to_ascii_lowercase());
    }
    result
}

fn ensure_python_plugin() -> Result<PathBuf> {
    if let Some(path) = find_python_plugin()? {
        info!("✅ Using installed framework_codegen_python");
        return Ok(path);
    }

    if let Some(path) = create_workspace_python_plugin_shim()? {
        info!("✅ Using workspace framework_codegen_python");
        return Ok(path);
    }

    Err(ActrCliError::command_error(
        "framework_codegen_python not found. Install it in your active environment, \
         for example: python -m pip install framework_codegen_python"
            .to_string(),
    ))
}

fn find_python_plugin() -> Result<Option<PathBuf>> {
    let output = StdCommand::new("which")
        .arg("framework_codegen_python")
        .output();

    match output {
        Ok(output) if output.status.success() => {
            let path = String::from_utf8_lossy(&output.stdout).trim().to_string();
            if path.is_empty() {
                Ok(None)
            } else {
                Ok(Some(PathBuf::from(path)))
            }
        }
        _ => Ok(None),
    }
}

fn create_workspace_python_plugin_shim() -> Result<Option<PathBuf>> {
    let cli_manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let Some(workspace_root) = cli_manifest_dir.parent() else {
        return Ok(None);
    };
    let package_dir = workspace_root.join("tools/protoc-gen/python");
    if !package_dir.join("framework_codegen_python").is_dir() {
        return Ok(None);
    }

    let python = if command_exists("python3") {
        "python3"
    } else if command_exists("python") {
        "python"
    } else {
        return Ok(None);
    };

    let shim_dir = std::env::temp_dir().join("actr-python-codegen");
    std::fs::create_dir_all(&shim_dir).map_err(|error| {
        ActrCliError::command_error(format!(
            "Failed to create Python plugin shim directory {}: {error}",
            shim_dir.display()
        ))
    })?;
    let shim_path = shim_dir.join("framework_codegen_python");
    let content = format!(
        "#!/usr/bin/env sh\nPYTHONPATH='{}' exec {} -m framework_codegen_python \"$@\"\n",
        package_dir.display(),
        python
    );
    std::fs::write(&shim_path, content).map_err(|error| {
        ActrCliError::command_error(format!(
            "Failed to write Python plugin shim {}: {error}",
            shim_path.display()
        ))
    })?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut permissions = std::fs::metadata(&shim_path)?.permissions();
        permissions.set_mode(0o755);
        std::fs::set_permissions(&shim_path, permissions)?;
    }

    Ok(Some(shim_path))
}

/// Check if the installed protobuf version meets the minimum requirement (>= 6.33.3)
fn check_python_protobuf_version(python_cmd: &str) -> Result<()> {
    info!("🔍 Checking protobuf version...");

    let output = StdCommand::new(python_cmd)
        .arg("-c")
        .arg("import google.protobuf; print(google.protobuf.__version__)")
        .output();

    match output {
        Ok(output) if output.status.success() => {
            let version_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
            info!("📦 Found protobuf version: {}", version_str);

            let version_parts: Vec<u32> = version_str
                .split('.')
                .filter_map(|s| s.parse().ok())
                .collect();

            let required_version = [6, 33, 3];
            let is_compatible = version_parts.len() >= 3
                && (version_parts[0] > required_version[0]
                    || (version_parts[0] == required_version[0]
                        && version_parts[1] > required_version[1])
                    || (version_parts[0] == required_version[0]
                        && version_parts[1] == required_version[1]
                        && version_parts[2] >= required_version[2]));

            if !is_compatible {
                warn!(
                    "⚠️  Protobuf version {} is older than required version 6.33.3",
                    version_str
                );
                warn!("   This may cause runtime errors when loading generated code.");
                warn!("   Please upgrade protobuf:");
                warn!("     pip install --upgrade 'protobuf>=6.33.3'");
                warn!("");
            } else {
                info!("✅ Protobuf version is compatible");
            }
        }
        _ => {
            warn!("⚠️  Could not detect protobuf version");
            warn!("   Please ensure protobuf >= 6.33.3 is installed:");
            warn!("     pip install 'protobuf>=6.33.3'");
            warn!("");
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    #[test]
    fn test_remote_path_extraction() {
        // Test the logic for extracting remote path after "/remote/"
        let test_cases = vec![
            (
                "protos/remote/server/service.proto",
                Some("server/service.proto"),
            ),
            // "remote/test.proto" will NOT match because split produces ["", "test.proto"]
            // which is only 2 parts, but the first part is empty, not what we want
            ("protos/remote/test.proto", Some("test.proto")),
            ("protos/local.proto", None),
            ("no_remote_here.proto", None),
        ];

        for (input, expected) in test_cases {
            let parts: Vec<&str> = input.split("/remote/").collect();
            let result = if parts.len() == 2 && !parts[0].is_empty() {
                Some(parts[1])
            } else {
                None
            };

            assert_eq!(
                result, expected,
                "Failed for input: {}, expected: {:?}, got: {:?}",
                input, expected, result
            );
        }
    }

    #[test]
    fn test_remote_services_map_construction() {
        // Create a simple mock lock file structure
        let mut remote_services_map: HashMap<String, String> = HashMap::new();

        // Simulate adding entries from lock file
        remote_services_map.insert(
            "server/service.proto".to_string(),
            "acme:TestServer".to_string(),
        );
        remote_services_map.insert(
            "api/v1/api.proto".to_string(),
            "custom:ApiService".to_string(),
        );

        // Verify the mapping
        assert_eq!(remote_services_map.len(), 2);
        assert_eq!(
            remote_services_map.get("server/service.proto"),
            Some(&"acme:TestServer".to_string())
        );
        assert_eq!(
            remote_services_map.get("api/v1/api.proto"),
            Some(&"custom:ApiService".to_string())
        );
    }

    #[test]
    fn test_options_string_building() {
        let remote_file_mappings = [
            "remote/s1.proto=testco:S1".to_string(),
            "remote/s2.proto=other:S2".to_string(),
        ];
        let local_paths = ["local.proto".to_string()];

        let mut options = String::new();

        if !remote_file_mappings.is_empty() {
            options.push_str(&format!(
                "RemoteFileMapping={}",
                remote_file_mappings.join(";")
            ));
        }

        if !local_paths.is_empty() {
            if !options.is_empty() {
                options.push(',');
            }
            options.push_str(&format!("LocalFiles={}", local_paths.join(":")));
        }

        assert!(
            options
                .contains("RemoteFileMapping=remote/s1.proto=testco:S1;remote/s2.proto=other:S2")
        );
        assert!(options.contains("LocalFiles=local.proto"));
    }

    #[test]
    fn test_actr_type_extraction_logic() {
        let remote_services_map: HashMap<String, String> = [
            (
                "service1/api.proto".to_string(),
                "mfg1:Service1".to_string(),
            ),
            (
                "service2/api.proto".to_string(),
                "mfg2:Service2".to_string(),
            ),
        ]
        .iter()
        .cloned()
        .collect();

        // Test matched path
        let path1 = "service1/api.proto";
        assert_eq!(
            remote_services_map.get(path1),
            Some(&"mfg1:Service1".to_string())
        );

        // Test unmatched path (should return None)
        let path2 = "unknown/api.proto";
        assert_eq!(remote_services_map.get(path2), None);

        // Test that we can handle None gracefully with empty string
        let actr_type = remote_services_map.get(path2).cloned().unwrap_or_default();
        assert_eq!(actr_type, "");
    }

    #[test]
    fn test_empty_lock_file_scenario() {
        // When lock file doesn't exist or has no dependencies
        let remote_services_map: HashMap<String, String> = HashMap::new();

        // Should handle gracefully
        assert_eq!(remote_services_map.len(), 0);
        assert_eq!(remote_services_map.get("any/path.proto"), None);

        // Simulating the warning path
        let _path_str = "remote/service/api.proto";
        let is_in_map = remote_services_map.contains_key("service/api.proto");
        assert!(!is_in_map);
        // In actual code, this triggers warn! and pushes empty string
    }
}