depyler 4.1.1

A Python-to-Rust transpiler focusing on energy-efficient, safe code generation with progressive verification
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
//! # Depyler - Python to Rust Transpiler
//!
//! Minimal CLI focused on transpilation and single-shot compilation.

use anyhow::Result;
use clap::{Parser, Subcommand};
use colored::Colorize;
use depyler_analyzer::Analyzer;
use depyler_core::DepylerPipeline;
use std::fs;
use std::path::PathBuf;

// Essential modules only
pub mod cli_shim;
pub mod compile_cmd;
pub mod converge;
pub mod dashboard_cmd;
pub mod graph_cmd;
pub mod lint_cmd;
pub mod report_cmd;
pub mod report_shim;
pub mod score_cmd;
pub mod transpile_shim;
pub mod utol_cmd;

// DEPYLER-1202: Trait Bridge for Python method compatibility
pub mod prelude;
pub mod python_ops;

#[derive(Parser)]
#[command(name = "depyler")]
#[command(about = "Pragmatic Python-to-Rust Transpiler", version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    #[arg(short, long, global = true)]
    pub verbose: bool,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Transpile Python code to Rust
    Transpile {
        /// Input Python file
        input: PathBuf,

        /// Output Rust file (defaults to input with .rs extension)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Enable verification
        #[arg(long)]
        verify: bool,

        /// Generate property tests
        #[arg(long)]
        gen_tests: bool,

        /// Enable debug mode
        #[arg(long)]
        debug: bool,

        /// Generate source map
        #[arg(long)]
        source_map: bool,
    },

    /// Compile Python to standalone binary
    Compile {
        /// Input Python file
        input: PathBuf,

        /// Output binary path (defaults to input name without extension)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Cargo build profile (debug, release)
        #[arg(long, default_value = "release")]
        profile: String,
    },

    /// Analyze Python code complexity and metrics
    Analyze {
        /// Input Python file
        input: PathBuf,

        /// Output format (json, text)
        #[arg(short, long, default_value = "text")]
        format: String,
    },

    /// Check if Python code can be transpiled
    Check {
        /// Input Python file
        input: PathBuf,
    },

    /// Automated convergence loop to achieve target compilation rate
    Converge {
        /// Directory containing Python examples
        #[arg(long)]
        input_dir: PathBuf,

        /// Target compilation rate (0-100)
        #[arg(long, default_value = "100")]
        target_rate: f64,

        /// Maximum iterations before stopping
        #[arg(long, default_value = "50")]
        max_iterations: usize,

        /// Automatically apply transpiler fixes
        #[arg(long)]
        auto_fix: bool,

        /// Show what would be fixed without applying
        #[arg(long)]
        dry_run: bool,

        /// Minimum confidence for auto-fix
        #[arg(long, default_value = "0.8")]
        fix_confidence: f64,

        /// Directory to save/resume state
        #[arg(long)]
        checkpoint: Option<PathBuf>,

        /// Number of parallel compilation jobs
        #[arg(long, default_value = "4")]
        jobs: usize,

        /// Display mode (rich, minimal, json, silent)
        #[arg(long, default_value = "rich")]
        display: String,

        /// Enable Oracle ML-based error classification
        #[arg(long)]
        oracle: bool,

        /// Enable explainability traces
        #[arg(long)]
        explain: bool,

        /// Enable O(1) compilation cache
        #[arg(long, default_value = "true")]
        cache: bool,

        /// DEPYLER-1308: Enable transpiler patching (modifies depyler-core source)
        #[arg(long)]
        patch_transpiler: bool,

        /// DEPYLER-1308: Path to APR file with custom patches
        #[arg(long)]
        apr_file: Option<PathBuf>,
    },

    /// Train Oracle on user corpus (DEPYLER-ORACLE-TRAIN)
    Train {
        /// Directory containing Python corpus to train on
        #[arg(long)]
        corpus: PathBuf,

        /// Output model path (default: ~/.depyler/oracle_user.bin)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Target compilation rate to achieve during training
        #[arg(long, default_value = "80")]
        target_rate: f64,

        /// Maximum training iterations
        #[arg(long, default_value = "10")]
        max_iterations: usize,
    },

    /// Generate deterministic corpus analysis report
    Report {
        /// Directory containing Python examples
        #[arg(long)]
        input_dir: PathBuf,

        /// Output format (text, json, markdown)
        #[arg(short, long, default_value = "text")]
        format: String,

        /// Output file (defaults to stdout)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Filter by error code (e.g., E0599)
        #[arg(long)]
        filter_error: Option<String>,

        /// Filter by file pattern (glob)
        #[arg(long)]
        filter_file: Option<String>,

        /// Only show failing files
        #[arg(long)]
        failures_only: bool,

        /// Show detailed error messages
        #[arg(long)]
        verbose: bool,
    },

    /// UTOL: Unified Training Oracle Loop
    Utol {
        /// Directory containing Python examples
        #[arg(long)]
        corpus: Option<PathBuf>,

        /// Target compilation rate (0.0-1.0)
        #[arg(long, default_value = "0.80")]
        target_rate: f64,

        /// Maximum iterations
        #[arg(long, default_value = "50")]
        max_iterations: usize,

        /// Patience before early stopping
        #[arg(long, default_value = "5")]
        patience: usize,

        /// Display mode (rich, minimal, json, silent)
        #[arg(long, default_value = "rich")]
        display: String,

        /// Show corpus status only
        #[arg(long)]
        status: bool,
    },

    /// Compilation cache commands
    #[command(subcommand)]
    Cache(CacheCommands),

    /// DEPYLER-1101: Repair type errors using Oracle-learned constraints
    Repair {
        /// Input Python file to repair
        input: PathBuf,

        /// Output Rust file (defaults to input with .rs extension)
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Maximum repair iterations
        #[arg(long, default_value = "10")]
        max_iterations: usize,

        /// Display verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// DEPYLER-1303: Graph-based error analysis
    #[command(subcommand)]
    Graph(GraphCommands),

    /// Corpus registry commands
    #[command(subcommand)]
    Corpus(CorpusCommands),

    /// DEPYLER-99MODE: Lint Python for Depyler Python compliance (Path A)
    Lint {
        /// Input Python file or directory
        input: PathBuf,

        /// Enable strict mode (Depyler Python subset only)
        #[arg(long)]
        strict: bool,

        /// Output format (text, json)
        #[arg(short, long, default_value = "text")]
        format: String,

        /// Fail on first error (stop-the-line)
        #[arg(long)]
        fail_fast: bool,

        /// Analyze corpus and report compliance percentage
        #[arg(long)]
        corpus: bool,
    },

    /// DEPYLER-DASH-001: Sovereign stack coverage dashboard
    Dashboard {
        /// Output format (text, json)
        #[arg(short, long, default_value = "text")]
        format: String,

        /// Filter to specific component (aprender, trueno, realizar)
        #[arg(long)]
        component: Option<String>,
    },
}

/// Graph analysis subcommands
#[derive(Subcommand)]
pub enum GraphCommands {
    /// Analyze corpus and identify Patient Zeros (high-impact failure points)
    Analyze {
        /// Directory containing Python examples
        #[arg(long)]
        corpus: PathBuf,

        /// Number of top Patient Zeros to identify
        #[arg(long, default_value = "5")]
        top: usize,

        /// Output file (JSON format)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Vectorize failures for ML training
    Vectorize {
        /// Directory containing Python examples
        #[arg(long)]
        corpus: PathBuf,

        /// Output file for vectorized failures
        #[arg(short, long)]
        output: PathBuf,

        /// Output format (json, ndjson)
        #[arg(long, default_value = "ndjson")]
        format: String,
    },
}

#[derive(Subcommand)]
pub enum CacheCommands {
    /// Show cache statistics
    Stats {
        /// Output format (text, json)
        #[arg(short, long, default_value = "text")]
        format: String,
    },

    /// Run garbage collection
    Gc {
        /// Maximum age in days for entries
        #[arg(long, default_value = "30")]
        max_age_days: u32,

        /// Dry run (show what would be deleted)
        #[arg(long)]
        dry_run: bool,
    },

    /// Clear the entire cache
    Clear {
        /// Skip confirmation
        #[arg(long)]
        force: bool,
    },

    /// Warm cache by pre-transpiling files
    Warm {
        /// Directory containing Python files
        #[arg(long)]
        input_dir: PathBuf,

        /// Number of parallel jobs
        #[arg(long, default_value = "4")]
        jobs: usize,
    },
}

/// Corpus registry subcommands
#[derive(Subcommand)]
pub enum CorpusCommands {
    /// List all registered corpora
    List {
        /// Output format (text, json)
        #[arg(short, long, default_value = "text")]
        format: String,

        /// Only show available (existing) corpora
        #[arg(long)]
        available: bool,
    },

    /// Show details of a specific corpus
    Show {
        /// Corpus name (e.g., reprorusted-std-only)
        name: String,
    },

    /// Add a corpus to the registry
    Add {
        /// Corpus name
        #[arg(long)]
        name: String,

        /// Path to the corpus directory
        #[arg(long)]
        path: PathBuf,

        /// Description of the corpus
        #[arg(long)]
        description: Option<String>,

        /// GitHub repository URL
        #[arg(long)]
        github: Option<String>,
    },
}

// ============================================================================
// Core Commands
// ============================================================================

pub fn transpile_command(
    input: PathBuf,
    output: Option<PathBuf>,
    verify: bool,
    gen_tests: bool,
    debug: bool,
    source_map: bool,
) -> Result<()> {
    use depyler_core::cargo_toml_gen::{generate_cargo_toml_auto, Dependency};

    let python_source = fs::read_to_string(&input)?;
    let pipeline = DepylerPipeline::new();

    // DEPYLER-0384: Use transpile_with_dependencies for automatic Cargo.toml emission
    let (rust_code, dependencies) = match pipeline.transpile_with_dependencies(&python_source) {
        Ok(result) => result,
        Err(err) => {
            let diagnostic = depyler_core::diagnostic::Diagnostic::from_anyhow(
                &err,
                Some(input.display().to_string()),
                Some(&python_source),
            );
            eprintln!("{}", diagnostic);
            anyhow::bail!("transpilation failed");
        }
    };

    let output_path = output.unwrap_or_else(|| input.with_extension("rs"));
    fs::write(&output_path, &rust_code)?;

    println!("{} {}", "✓".green(), output_path.display());

    // DEPYLER-0384: Automatically emit Cargo.toml for single-shot compile guarantee
    // Always emit regardless of detected dependencies
    {
        let package_name = output_path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("transpiled")
            .replace('-', "_"); // Cargo package names use underscores

        let source_file_name = output_path
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("main.rs");

        // Convert dependencies to cargo_toml_gen::Dependency type
        let deps: Vec<Dependency> = dependencies;

        let cargo_toml = generate_cargo_toml_auto(&package_name, source_file_name, &deps);

        // Write Cargo.toml in the same directory as the output file
        let cargo_toml_path = output_path
            .parent()
            .unwrap_or(std::path::Path::new("."))
            .join("Cargo.toml");
        fs::write(&cargo_toml_path, cargo_toml)?;

        println!(
            "{} {} (with {} dependencies)",
            "✓".green(),
            cargo_toml_path.display(),
            deps.len()
        );
    }

    if verify {
        println!("Verification not yet implemented");
    }

    if gen_tests {
        println!("Test generation not yet implemented");
    }

    if debug {
        println!("Debug mode enabled");
    }

    if source_map {
        println!("Source map generation not yet implemented");
    }

    Ok(())
}

pub fn compile_command(input: PathBuf, output: Option<PathBuf>, profile: String) -> Result<()> {
    let output_ref = output.as_deref();
    let profile_ref = if profile.is_empty() {
        None
    } else {
        Some(profile.as_str())
    };
    compile_cmd::compile_python_to_binary(&input, output_ref, profile_ref)?;
    Ok(())
}

pub fn analyze_command(input: PathBuf, format: String) -> Result<()> {
    let python_source = fs::read_to_string(&input)?;
    let pipeline = DepylerPipeline::new();
    let hir = pipeline.parse_to_hir(&python_source)?;
    let analyzer = Analyzer::new();
    let report = analyzer.analyze(&hir)?;

    match format.as_str() {
        "json" => println!("{}", serde_json::to_string_pretty(&report)?),
        _ => println!("{:#?}", report),
    }

    Ok(())
}

pub fn check_command(input: PathBuf) -> Result<()> {
    let python_source = fs::read_to_string(&input)?;
    let pipeline = DepylerPipeline::new();

    match pipeline.transpile(&python_source) {
        Ok(_) => {
            println!("{} {} can be transpiled", "✓".green(), input.display());
            Ok(())
        }
        Err(e) => {
            let diagnostic = depyler_core::diagnostic::Diagnostic::from_anyhow(
                &e,
                Some(input.display().to_string()),
                Some(&python_source),
            );
            eprintln!("{}", diagnostic);
            anyhow::bail!("check failed")
        }
    }
}

/// DEPYLER-1101: Repair type errors using Oracle-learned constraints.
///
/// This command implements a "Transpile → Compile → Learn → Fix" loop that:
/// 1. Transpiles Python to Rust
/// 2. Attempts compilation to detect E0308 type mismatch errors
/// 3. Learns correct types from compiler error messages
/// 4. Re-transpiles with learned type constraints
/// 5. Repeats until compilation succeeds or max iterations reached
pub fn repair_command(
    input: PathBuf,
    output: Option<PathBuf>,
    max_iterations: usize,
    verbose: bool,
) -> Result<()> {
    use depyler_oracle::utol::repair_file_types;

    if verbose {
        println!(
            "{} Starting type repair for {}",
            "🔧".green(),
            input.display()
        );
        println!("   Max iterations: {}", max_iterations);
    }

    let result = repair_file_types(&input, max_iterations)?;

    if result.success {
        println!(
            "{} {} repaired successfully in {} iterations",
            "✓".green(),
            input.display(),
            result.iterations
        );
        println!(
            "   Constraints learned: {}, applied: {}",
            result.constraints_learned, result.constraints_applied
        );

        // If successful, read the generated Rust code and write to output
        let pipeline = DepylerPipeline::new();
        let python_source = fs::read_to_string(&input)?;

        // Get the learned constraints from the final iteration
        // For now, just transpile again (constraints were already applied internally)
        let rust_code = pipeline.transpile(&python_source)?;

        let output_path = output.unwrap_or_else(|| input.with_extension("rs"));
        fs::write(&output_path, &rust_code)?;

        println!(
            "{} Wrote repaired Rust code to {}",
            "📄".green(),
            output_path.display()
        );

        Ok(())
    } else {
        println!(
            "{} {} repair failed after {} iterations",
            "✗".red(),
            input.display(),
            result.iterations
        );
        println!(
            "   Constraints learned: {}, applied: {}",
            result.constraints_learned, result.constraints_applied
        );
        println!("   Final compile rate: {:.1}%", result.final_rate * 100.0);

        anyhow::bail!(
            "Type repair failed after {} iterations. Consider manual fixes.",
            max_iterations
        )
    }
}

// ============================================================================
// Helpers
// ============================================================================

pub fn complexity_rating(complexity: f64) -> colored::ColoredString {
    if complexity < 10.0 {
        "Low".green()
    } else if complexity < 20.0 {
        "Medium".yellow()
    } else {
        "High".red()
    }
}

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

    #[test]
    fn test_complexity_rating_low() {
        let rating = complexity_rating(5.0);
        assert!(!rating.to_string().is_empty());
    }

    #[test]
    fn test_complexity_rating_medium() {
        let rating = complexity_rating(15.0);
        assert!(!rating.to_string().is_empty());
    }

    #[test]
    fn test_complexity_rating_high() {
        let rating = complexity_rating(25.0);
        assert!(!rating.to_string().is_empty());
    }

    #[test]
    fn test_complexity_rating_boundary_low() {
        let rating = complexity_rating(9.99);
        assert!(rating.to_string().contains("Low"));
    }

    #[test]
    fn test_complexity_rating_boundary_medium() {
        let rating = complexity_rating(10.0);
        assert!(rating.to_string().contains("Medium"));
    }

    #[test]
    fn test_complexity_rating_boundary_high() {
        let rating = complexity_rating(20.0);
        assert!(rating.to_string().contains("High"));
    }

    #[test]
    fn test_complexity_rating_zero() {
        let rating = complexity_rating(0.0);
        assert!(rating.to_string().contains("Low"));
    }

    #[test]
    fn test_complexity_rating_negative() {
        let rating = complexity_rating(-5.0);
        assert!(rating.to_string().contains("Low"));
    }

    #[test]
    fn test_transpile_command_valid() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        fs::write(
            &py_file,
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();

        let result = transpile_command(py_file.clone(), None, false, false, false, false);
        assert!(result.is_ok());

        let rs_file = py_file.with_extension("rs");
        assert!(rs_file.exists());
    }

    #[test]
    fn test_transpile_command_with_output() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        let rs_file = temp.path().join("custom_output.rs");
        fs::write(&py_file, "def greet() -> str:\n    return 'hello'\n").unwrap();

        let result = transpile_command(py_file, Some(rs_file.clone()), false, false, false, false);
        assert!(result.is_ok());
        assert!(rs_file.exists());
    }

    #[test]
    fn test_transpile_command_nonexistent() {
        let result = transpile_command(
            PathBuf::from("/nonexistent.py"),
            None,
            false,
            false,
            false,
            false,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_transpile_command_with_verify() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        fs::write(&py_file, "x = 1\n").unwrap();

        let result = transpile_command(py_file, None, true, false, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_transpile_command_with_gen_tests() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        fs::write(&py_file, "x = 1\n").unwrap();

        let result = transpile_command(py_file, None, false, true, false, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_transpile_command_with_debug() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        fs::write(&py_file, "x = 1\n").unwrap();

        let result = transpile_command(py_file, None, false, false, true, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_transpile_command_with_source_map() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        fs::write(&py_file, "x = 1\n").unwrap();

        let result = transpile_command(py_file, None, false, false, false, true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_transpile_command_all_flags() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("test.py");
        fs::write(&py_file, "def foo(): pass\n").unwrap();

        let result = transpile_command(py_file, None, true, true, true, true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_analyze_command_text_format() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("analyze.py");
        fs::write(
            &py_file,
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();

        let result = analyze_command(py_file, "text".to_string());
        assert!(result.is_ok());
    }

    #[test]
    fn test_analyze_command_json_format() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("analyze.py");
        fs::write(
            &py_file,
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();

        let result = analyze_command(py_file, "json".to_string());
        assert!(result.is_ok());
    }

    #[test]
    fn test_analyze_command_nonexistent() {
        let result = analyze_command(PathBuf::from("/nonexistent.py"), "text".to_string());
        assert!(result.is_err());
    }

    #[test]
    fn test_check_command_valid() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("check.py");
        fs::write(
            &py_file,
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();

        let result = check_command(py_file);
        assert!(result.is_ok());
    }

    #[test]
    fn test_check_command_nonexistent() {
        let result = check_command(PathBuf::from("/nonexistent.py"));
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_command_nonexistent() {
        let result = compile_command(
            PathBuf::from("/nonexistent.py"),
            None,
            "release".to_string(),
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_compile_command_empty_profile() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("compile.py");
        fs::write(&py_file, "def foo(): pass\n").unwrap();

        // Empty profile - should use None internally
        let result = compile_command(py_file, None, "".to_string());
        // May fail during actual compilation, but should not panic
        let _ = result;
    }

    #[test]
    fn test_compile_command_with_profile() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("compile.py");
        fs::write(&py_file, "def foo(): pass\n").unwrap();

        let result = compile_command(py_file, None, "debug".to_string());
        // May fail during actual compilation, but should not panic
        let _ = result;
    }

    // CLI struct tests
    #[test]
    fn test_cli_verbose_default() {
        use clap::Parser;
        let cli = Cli::try_parse_from(["depyler", "check", "test.py"]).unwrap();
        assert!(!cli.verbose);
    }

    #[test]
    fn test_cache_commands_stats() {
        use clap::Parser;
        let cli = Cli::try_parse_from(["depyler", "cache", "stats"]).unwrap();
        if let Commands::Cache(CacheCommands::Stats { format }) = cli.command {
            assert_eq!(format, "text");
        } else {
            panic!("Expected Cache Stats");
        }
    }

    #[test]
    fn test_cache_commands_gc() {
        use clap::Parser;
        let cli = Cli::try_parse_from(["depyler", "cache", "gc"]).unwrap();
        if let Commands::Cache(CacheCommands::Gc {
            max_age_days,
            dry_run,
        }) = cli.command
        {
            assert_eq!(max_age_days, 30);
            assert!(!dry_run);
        } else {
            panic!("Expected Cache Gc");
        }
    }

    #[test]
    fn test_cache_commands_clear() {
        use clap::Parser;
        let cli = Cli::try_parse_from(["depyler", "cache", "clear"]).unwrap();
        if let Commands::Cache(CacheCommands::Clear { force }) = cli.command {
            assert!(!force);
        } else {
            panic!("Expected Cache Clear");
        }
    }

    #[test]
    fn test_cache_commands_warm() {
        use clap::Parser;
        let cli = Cli::try_parse_from(["depyler", "cache", "warm", "--input-dir", "/tmp"]).unwrap();
        if let Commands::Cache(CacheCommands::Warm { input_dir, jobs }) = cli.command {
            assert_eq!(input_dir, PathBuf::from("/tmp"));
            assert_eq!(jobs, 4);
        } else {
            panic!("Expected Cache Warm");
        }
    }

    // ========================================================================
    // Session 11 - Deep Coverage Tests
    // ========================================================================

    #[test]
    fn test_complexity_rating_infinity() {
        let rating = complexity_rating(f64::INFINITY);
        assert!(rating.to_string().contains("High"));
    }

    #[test]
    fn test_complexity_rating_large() {
        let rating = complexity_rating(1e10);
        assert!(rating.to_string().contains("High"));
    }

    #[test]
    fn test_complexity_rating_nan() {
        // NaN < 10.0 is false, NaN < 20.0 is false, falls through to High
        let rating = complexity_rating(f64::NAN);
        assert!(rating.to_string().contains("High"));
    }

    #[test]
    fn test_transpile_command_with_cargo_toml() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("lib_test.py");
        fs::write(
            &py_file,
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();

        let output = temp.path().join("lib_test.rs");
        let result = transpile_command(py_file, Some(output.clone()), false, false, false, false);
        assert!(result.is_ok());
        assert!(output.exists());
        // Cargo.toml should be generated alongside the output
        let cargo_toml = temp.path().join("Cargo.toml");
        assert!(cargo_toml.exists());
    }

    #[test]
    fn test_check_command_invalid_syntax() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("bad_syntax.py");
        fs::write(&py_file, "def @@@invalid syntax!!!").unwrap();

        let result = check_command(py_file);
        assert!(result.is_err());
    }

    #[test]
    fn test_analyze_command_unknown_format() {
        let temp = TempDir::new().unwrap();
        let py_file = temp.path().join("analyze.py");
        fs::write(
            &py_file,
            "def add(a: int, b: int) -> int:\n    return a + b\n",
        )
        .unwrap();

        // Unknown format falls through to debug print
        let result = analyze_command(py_file, "xml".to_string());
        assert!(result.is_ok());
    }
}