fastshell 0.3.6

Lightweight Bash + Python runtime SDK for mobile AI agents
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
// Copyright (c) 2025 xiefujin <490021684@qq.com>
// Licensed under Apache-2.0, see LICENSE file for full license terms.

use crate::shell::{CommandOutput, Shell};
use std::io::Cursor;

const PIP_INSTALL_HELP: &str = "\
Usage: pip install [PACKAGE]...
       pip-install [PACKAGE]...
       pip3 install [PACKAGE]...
       python3 -m pip install [PACKAGE]...
       pip list | pip freeze | pip show NAME | pip uninstall NAME

Install pure-Python packages from PyPI into site-packages/.

Only py3-none-any.whl (pure Python, no C extensions) are accepted.
Packages with .so/.pyd files are rejected with an error.

Networking uses the same HTTP stack as `curl` (with retries). Set
FASTSHELL_PYPI_INDEX to use a mirror (e.g. https://pypi.tuna.tsinghua.edu.cn).

Options:
  -l, --list   list installed packages
  -h, --help   display this help and exit
";

impl Shell {
    pub fn cmd_pip_install(&self, args: &[&str]) -> CommandOutput {
        let mut packages = Vec::new();
        let mut list_mode = false;

        let mut i = 0;
        while i < args.len() {
            match args[i] {
                "-h" | "--help" => return CommandOutput::success(PIP_INSTALL_HELP.to_string()),
                "-l" | "--list" | "list" => list_mode = true,
                "-r" | "--requirement" => {
                    if i + 1 < args.len() {
                        if let Ok(content) = self.read_text_lossy(args[i + 1]) {
                            for line in content.lines() {
                                let l = line.trim();
                                if !l.is_empty() && !l.starts_with('#') {
                                    packages.push(l.to_string());
                                }
                            }
                        }
                        i += 1;
                    }
                }
                // `-U`/`--upgrade`/`-q`/`-y` etc. are accepted and ignored.
                a if a.starts_with('-') => {}
                a => packages.push(a.to_string()),
            }
            i += 1;
        }

        if list_mode {
            return self.cmd_pip_list();
        }

        if packages.is_empty() {
            return CommandOutput::error("pip-install: missing package name(s)\n".to_string(), 1);
        }

        let cache_dir = std::env::var("FASTSHELL_WHEEL_CACHE")
            .ok()
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|| std::path::PathBuf::from(".wheel_cache"));

        let site_dir = "site-packages";

        let mut output = String::new();
        let mut failures = 0;

        for pkg in &packages {
            match install_package(pkg, &cache_dir, site_dir, &self.vfs, &self.cwd) {
                Ok(msg) => {
                    output.push_str(&format!("installed {}\n", pkg));
                    if !msg.is_empty() {
                        output.push_str(&format!("  {}\n", msg));
                    }
                }
                Err(e) => {
                    output.push_str(&format!("{}: error: {}\n", pkg, e));
                    failures += 1;
                }
            }
        }

        if failures > 0 {
            CommandOutput::error(output, 1)
        } else {
            CommandOutput::success(output)
        }
    }

    /// Unified `pip` entry — shared by the `pip` command, `pip3`, and
    /// `python3 -m pip …`, so sub-commands behave identically everywhere.
    pub fn cmd_pip(&mut self, args: &[&str]) -> CommandOutput {
        match args.first().copied() {
            Some("install") => self.cmd_pip_install(&args[1..]),
            Some("list") | Some("freeze") => self.cmd_pip_install(&["--list"]),
            Some("show") => match args.get(1) {
                Some(n) => self.cmd_pip_show(n),
                None => {
                    CommandOutput::error("ERROR: pip show requires a package name.\n".into(), 1)
                }
            },
            Some("uninstall") => match args.get(1) {
                Some(n) => self.cmd_pip_uninstall(n),
                None => CommandOutput::error(
                    "ERROR: pip uninstall requires a package name.\n".into(),
                    1,
                ),
            },
            Some("-h") | Some("--help") | None => self.cmd_pip_install(&["-h"]),
            _ => CommandOutput::error(
                "pip: supported: install/list/freeze/show/uninstall.\n".to_string(),
                1,
            ),
        }
    }

    /// `pip show NAME` — print metadata for an installed package.
    pub fn cmd_pip_show(&self, name: &str) -> CommandOutput {
        let site_dir = "site-packages";
        let entries = match self.vfs.list_dir(site_dir, &self.cwd) {
            Ok(e) => e,
            Err(_) => {
                return CommandOutput::error(
                    format!("WARNING: Package(s) not found: {}\n", name),
                    1,
                )
            }
        };
        let lower = name.to_lowercase();
        let dist = entries.iter().find(|e| {
            e.is_dir
                && e.name.ends_with(".dist-info")
                && e.name.to_lowercase().starts_with(&format!("{}-", lower))
        });
        match dist {
            None => CommandOutput::error(format!("WARNING: Package(s) not found: {}\n", name), 1),
            Some(d) => {
                let md = self
                    .vfs
                    .read_to_string(&format!("{}/{}/METADATA", site_dir, d.name), &self.cwd)
                    .unwrap_or_default();
                let mut out = String::new();
                for line in md.lines() {
                    if line.starts_with("Name:")
                        || line.starts_with("Version:")
                        || line.starts_with("Summary:")
                        || line.starts_with("Home-page:")
                        || line.starts_with("Author:")
                        || line.starts_with("License:")
                    {
                        out.push_str(line);
                        out.push('\n');
                    }
                }
                if out.is_empty() {
                    out = format!("Name: {}\n", name);
                }
                CommandOutput::success(out + "\n")
            }
        }
    }

    /// `pip uninstall NAME` — remove an installed package (best effort).
    pub fn cmd_pip_uninstall(&mut self, name: &str) -> CommandOutput {
        let site_dir = "site-packages";
        let entries = self.vfs.list_dir(site_dir, &self.cwd).unwrap_or_default();
        let lower = name.to_lowercase();
        let mut removed = false;

        // Remove the versioned dist-info directory.
        for e in &entries {
            if e.is_dir
                && e.name.ends_with(".dist-info")
                && e.name.to_lowercase().starts_with(&format!("{}-", lower))
            {
                let _ = self
                    .vfs
                    .remove_dir_all(&format!("{}/{}", site_dir, e.name), &self.cwd);
                removed = true;
            }
        }
        // Remove the module directory / single-file module.
        for e in &entries {
            let dir_match = e.is_dir && e.name.to_lowercase() == lower;
            let file_match = !e.is_dir && e.name.to_lowercase() == format!("{}.py", lower);
            if dir_match {
                let _ = self
                    .vfs
                    .remove_dir_all(&format!("{}/{}", site_dir, e.name), &self.cwd);
                removed = true;
            } else if file_match {
                let _ = self
                    .vfs
                    .remove_file(&format!("{}/{}", site_dir, e.name), &self.cwd);
                removed = true;
            }
        }

        if removed {
            CommandOutput::success(format!("Successfully uninstalled {}\n", name))
        } else {
            CommandOutput::error(
                format!("WARNING: Skipping {} as it is not installed.\n", name),
                1,
            )
        }
    }

    fn cmd_pip_list(&self) -> CommandOutput {
        let site_dir = "site-packages";
        let entries = match self.vfs.list_dir(site_dir, &self.cwd) {
            Ok(e) => e,
            Err(_) => return CommandOutput::success("(no packages installed)\n".to_string()),
        };

        let mut installed: std::collections::HashSet<String> = std::collections::HashSet::new();

        for entry in &entries {
            // Skip Python bytecode cache and other metadata dirs.
            if entry.name == "__pycache__" || entry.name == "site-packages" {
                continue;
            }
            if entry.is_dir {
                if entry.name.ends_with(".dist-info") {
                    // dist-info dir name is versioned (e.g. six-1.17.0.dist-info).
                    // Read the true package name from METADATA; fall back to
                    // stripping the version suffix from the dir name.
                    let metadata_path = format!("{}/{}/METADATA", site_dir, entry.name);
                    let pkg_name = self
                        .vfs
                        .read_to_string(&metadata_path, &self.cwd)
                        .ok()
                        .and_then(|c| extract_name_from_metadata(&c))
                        .unwrap_or_else(|| strip_dist_info_version(&entry.name));
                    if !pkg_name.is_empty() {
                        installed.insert(pkg_name);
                    }
                } else {
                    installed.insert(entry.name.clone());
                }
            } else if entry.name.ends_with(".py") {
                // Single-file module — recognized by a matching versioned
                // dist-info dir (e.g. six.py ↔ six-1.17.0.dist-info).
                let module_name = entry.name.trim_end_matches(".py");
                let has_dist_info = entries.iter().any(|e| {
                    e.is_dir
                        && e.name.ends_with(".dist-info")
                        && e.name.starts_with(&format!("{}-", module_name))
                });
                if has_dist_info {
                    installed.insert(module_name.to_string());
                }
            }
        }

        if installed.is_empty() {
            return CommandOutput::success("(no packages installed)\n".to_string());
        }

        let mut names: Vec<&String> = installed.iter().collect();
        names.sort();

        let mut output = String::new();
        for name in names {
            output.push_str(&format!("{}\n", name));
        }
        CommandOutput::success(output)
    }
}

/// PyPI index base. Override for a mirror via `FASTSHELL_PYPI_INDEX`
/// (e.g. `https://pypi.tuna.tsinghua.edu.cn`).
fn pypi_base() -> String {
    std::env::var("FASTSHELL_PYPI_INDEX")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| "https://pypi.org".to_string())
}

/// HTTP GET through the SAME network stack as `curl` (shared `http_request_ex`),
/// with a few retries to ride out transient route/DNS hiccups. This replaces the
/// previous bespoke ureq+TLS client, which was the source of the device-only
/// `ENETUNREACH` flakiness.
fn pip_http_get(url: &str, what: &str) -> Result<Vec<u8>, String> {
    use crate::shell::commands::curl::{http_request_ex, HttpConfig};
    let mut last = String::new();
    for attempt in 0..3u32 {
        let cfg = HttpConfig {
            method: "GET".to_string(),
            url: url.to_string(),
            follow_redirects: true,
            request_timeout_secs: 60.0,
            connect_timeout_secs: 15.0,
            ..Default::default()
        };
        match http_request_ex(&cfg) {
            Ok(r) => return Ok(r.body),
            Err(e) => last = e.message.clone(),
        }
        std::thread::sleep(std::time::Duration::from_millis(
            300 * u64::from(attempt + 1),
        ));
    }
    Err(format!("{what}: {last}"))
}

fn install_package(
    pkg: &str,
    cache_dir: &std::path::Path,
    site_dir: &str,
    vfs: &crate::vfs::Vfs,
    cwd: &str,
) -> Result<String, String> {
    // 1. Parse package name and optional version
    let (pkg_name, version) = parse_pkg_spec(pkg);

    // 2. Query PyPI
    let info = fetch_pypi_info(pkg_name)?;

    // 3. Find the best matching wheel for the requested version (or latest)
    let wheel_file = find_best_wheel(&info, version).ok_or_else(|| {
        if let Some(v) = version {
            format!("no py3-none-any.whl found for {} version {}", pkg_name, v)
        } else {
            format!(
                "no py3-none-any.whl found for {} (may require C extensions or single-file wheel)",
                pkg_name
            )
        }
    })?;

    let wheel_url = &wheel_file.url;
    let wheel_name = wheel_url.rsplit('/').next().unwrap_or(pkg_name);

    // 4. Check cache
    let cached = cache_dir.join(wheel_name);
    let wheel_data = if cached.exists() {
        let mut data = Vec::new();
        std::io::Read::read_to_end(
            &mut std::fs::File::open(&cached).map_err(|e| e.to_string())?,
            &mut data,
        )
        .map_err(|e| e.to_string())?;
        data
    } else {
        // 5. Download (same network stack as curl, with retries)
        let data = pip_http_get(wheel_url, "download failed")?;

        // Save to cache
        if let Some(parent) = cached.parent() {
            let _ = std::fs::create_dir_all(parent);
            let _ = std::fs::write(&cached, &data);
        }
        data
    };

    // 6. Validate — scan for C extensions
    validate_pure_python_wheel(&wheel_data, pkg_name)?;

    // 7. Extract
    extract_wheel(&wheel_data, site_dir, vfs, cwd)?;

    Ok(String::new())
}

struct WheelFile {
    filename: String,
    url: String,
}

fn parse_pkg_spec(pkg: &str) -> (&str, Option<&str>) {
    if let Some(pos) = pkg.find("==") {
        (&pkg[..pos], Some(&pkg[pos + 2..]))
    } else {
        (pkg, None)
    }
}

/// Extract the `Name:` field from a wheel METADATA file.
fn extract_name_from_metadata(content: &str) -> Option<String> {
    for line in content.lines() {
        if let Some(v) = line.strip_prefix("Name:") {
            let name = v.trim();
            if !name.is_empty() {
                return Some(name.to_string());
            }
        }
    }
    None
}

/// Fallback package-name extraction from a versioned dist-info dir name
/// (e.g. `six-1.17.0.dist-info` → `six`,
/// `charset-normalizer-3.5.0.dist-info` → `charset-normalizer`). Scans from
/// the right for a `-` followed by a digit (the version), so names containing
/// hyphens survive.
fn strip_dist_info_version(dist_info: &str) -> String {
    let base = dist_info.trim_end_matches(".dist-info");
    for (i, ch) in base.char_indices().rev() {
        if ch == '-' {
            let rest = &base[i + 1..];
            if rest.chars().next().map_or(false, |c| c.is_ascii_digit()) {
                return base[..i].to_string();
            }
        }
    }
    base.to_string()
}

fn find_best_wheel<'a>(info: &'a [WheelFile], version: Option<&str>) -> Option<&'a WheelFile> {
    let candidates: Vec<&WheelFile> = info
        .iter()
        .filter(|f| {
            let name = &f.filename;
            // Accept pure-Python wheels (any py* tag, "none" ABI, "any" platform)
            // e.g. *-py3-none-any.whl, *-py2.py3-none-any.whl
            name.contains("-none-any.whl")
        })
        .collect();

    if let Some(ver) = version {
        candidates
            .into_iter()
            .rev()
            .find(|f| f.filename.contains(ver))
    } else {
        candidates.into_iter().last()
    }
}

fn fetch_pypi_info(pkg: &str) -> Result<Vec<WheelFile>, String> {
    let url = format!("{}/pypi/{}/json", pypi_base().trim_end_matches('/'), pkg);
    let body = pip_http_get(&url, "PyPI query failed")?;

    let json: serde_json::Value =
        serde_json::from_slice(&body).map_err(|e| format!("PyPI JSON parse error: {}", e))?;

    let mut result = Vec::new();
    let releases = json["releases"].as_object().ok_or("no releases field")?;

    // Process versions in order
    let mut versions: Vec<&String> = releases.keys().collect();
    versions.sort_by_key(|v| parse_version(v));

    for ver in &versions {
        if let Some(files) = releases[*ver].as_array() {
            for file in files {
                let filename = file["filename"].as_str().unwrap_or("");
                let url = file["url"].as_str().unwrap_or("");
                if !filename.is_empty() && !url.is_empty() {
                    result.push(WheelFile {
                        filename: filename.to_string(),
                        url: url.to_string(),
                    });
                }
            }
        }
    }

    if result.is_empty() {
        return Err(format!("no releases found for {}", pkg));
    }

    Ok(result)
}

fn parse_version(v: &str) -> Vec<i64> {
    v.split(|c: char| !c.is_ascii_digit())
        .filter(|s| !s.is_empty())
        .filter_map(|s| s.parse::<i64>().ok())
        .collect()
}

fn validate_pure_python_wheel(data: &[u8], pkg: &str) -> Result<(), String> {
    let cursor = Cursor::new(data);
    let mut archive = zip::ZipArchive::new(cursor).map_err(|e| format!("bad wheel file: {}", e))?;

    for i in 0..archive.len() {
        let entry = archive
            .by_index(i)
            .map_err(|e| format!("read wheel: {}", e))?;
        let name = entry.name();
        if name.ends_with(".so") || name.ends_with(".pyd") {
            return Err(format!(
                "{} contains compiled C extension ({}) — cannot install on RustPython. Only pure-Python packages (py3-none-any.whl) are supported.",
                pkg, name
            ));
        }
    }

    Ok(())
}

fn extract_wheel(
    data: &[u8],
    site_dir: &str,
    vfs: &crate::vfs::Vfs,
    cwd: &str,
) -> Result<(), String> {
    let cursor = Cursor::new(data);
    let mut archive = zip::ZipArchive::new(cursor).map_err(|e| format!("bad wheel file: {}", e))?;

    // Classify: single-file module (e.g. six.py) or directory package
    let (is_single_file, pkg_root) = classify_package(&mut archive)?;

    if is_single_file {
        // Single-file module: extract directly into site-packages/
        // e.g. six.py → site-packages/six.py
        extract_single_file_wheel(&mut archive, &pkg_root, site_dir, vfs, cwd)?;
    } else {
        // Directory package: extract into site-packages/<module-dir>/.
        // Use the wheel's actual module directory name (pkg_root), NOT the
        // distribution name (pkg_name). They differ for many packages
        // (charset-normalizer → charset_normalizer, python-dateutil → dateutil,
        // pyyaml → yaml, beautifulsoup4 → bs4), and Python imports by the
        // module name — a dir named with a hyphen would be unimportable.
        let dest_dir = format!("{}/{}", site_dir, pkg_root);
        extract_directory_wheel(&mut archive, &pkg_root, &dest_dir, site_dir, vfs, cwd)?;
    }

    Ok(())
}

fn classify_package<R: std::io::Read + std::io::Seek>(
    archive: &mut zip::ZipArchive<R>,
) -> Result<(bool, String), String> {
    let mut pkg_root = String::new();
    let mut has_dir_entry = false;

    for i in 0..archive.len() {
        let entry = archive
            .by_index(i)
            .map_err(|e| format!("read wheel: {}", e))?;
        let name = entry.name().to_string();

        if name.contains(".dist-info/") || name.contains(".data/") {
            continue;
        }

        let top = name.split('/').next().unwrap_or("");
        if top.is_empty() || top.ends_with(".dist-info") || top.ends_with(".data") {
            continue;
        }

        if pkg_root.is_empty() {
            pkg_root = top.to_string();
        }

        if name.contains('/') && name != format!("{}/", pkg_root) {
            has_dir_entry = true;
        }
    }

    if pkg_root.is_empty() {
        return Err("wheel contains no installable files".to_string());
    }

    // Single-file: top is a .py file and no subdirectory entries exist
    let is_single_file = !has_dir_entry && pkg_root.ends_with(".py");

    Ok((is_single_file, pkg_root))
}

fn extract_single_file_wheel<R: std::io::Read + std::io::Seek>(
    archive: &mut zip::ZipArchive<R>,
    pkg_root: &str,
    site_dir: &str,
    vfs: &crate::vfs::Vfs,
    cwd: &str,
) -> Result<(), String> {
    // Ensure site-packages directory exists
    let _ = vfs.create_dir_all(site_dir, cwd);

    for i in 0..archive.len() {
        let mut entry = archive
            .by_index(i)
            .map_err(|e| format!("read wheel: {}", e))?;
        let name = entry.name().to_string();

        if entry.is_dir() {
            continue;
        }

        if name.contains(".dist-info/") {
            // Keep the wheel's original dist-info dir name (includes the
            // version, e.g. `six-1.17.0.dist-info`) instead of inventing
            // `six.dist-info`. Mirrors what real pip does.
            let out_path = format!("{}/{}", site_dir, name);
            let mut content = Vec::new();
            std::io::Read::read_to_end(&mut entry, &mut content)
                .map_err(|e| format!("read wheel entry {}: {}", name, e))?;
            if let Some(parent) = std::path::Path::new(&out_path).parent() {
                let _ = vfs.create_dir_all(&parent.to_string_lossy(), cwd);
            }
            vfs.write_bytes(&out_path, cwd, &content)
                .map_err(|e| format!("write {}: {}", out_path, e))?;
            continue;
        }

        if name.contains(".data/") {
            continue;
        }

        // The actual module file: extract as site-packages/<filename>
        let out_path = format!("{}/{}", site_dir, pkg_root);
        let mut content = Vec::new();
        std::io::Read::read_to_end(&mut entry, &mut content)
            .map_err(|e| format!("read wheel entry {}: {}", name, e))?;
        vfs.write_bytes(&out_path, cwd, &content)
            .map_err(|e| format!("write {}: {}", out_path, e))?;
    }

    Ok(())
}

fn extract_directory_wheel<R: std::io::Read + std::io::Seek>(
    archive: &mut zip::ZipArchive<R>,
    pkg_dir: &str,
    dest_dir: &str,
    site_dir: &str,
    vfs: &crate::vfs::Vfs,
    cwd: &str,
) -> Result<(), String> {
    let pkg_prefix = format!("{}/", pkg_dir);

    for i in 0..archive.len() {
        let mut entry = archive
            .by_index(i)
            .map_err(|e| format!("read wheel: {}", e))?;
        let name = entry.name().to_string();

        if name.contains(".data/") {
            continue;
        }

        let is_dist_info = name.contains(".dist-info/");

        let relative = if name.starts_with(&pkg_prefix) && pkg_prefix.len() > 0 {
            &name[pkg_prefix.len()..]
        } else if name == pkg_dir || name == format!("{}/", pkg_dir) {
            continue;
        } else {
            &name
        };

        // dist-info lives at the top level of site-packages (keeps the
        // wheel's versioned name, e.g. `requests-2.31.0.dist-info`), while
        // package files go under `dest_dir` (site-packages/<module>).
        let out_path = if is_dist_info {
            format!("{}/{}", site_dir, name)
        } else {
            format!("{}/{}", dest_dir, relative)
        };
        if entry.is_dir() {
            let _ = vfs.create_dir(&out_path, cwd);
            continue;
        }

        let mut content = Vec::new();
        std::io::Read::read_to_end(&mut entry, &mut content)
            .map_err(|e| format!("read wheel entry {}: {}", name, e))?;

        if let Some(parent) = std::path::Path::new(&out_path).parent() {
            let parent_str = parent.to_string_lossy();
            if !parent_str.is_empty() {
                let _ = vfs.create_dir_all(&parent_str, cwd);
            }
        }

        vfs.write_bytes(&out_path, cwd, &content)
            .map_err(|e| format!("write {}: {}", out_path, e))?;
    }

    Ok(())
}

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

    #[test]
    fn test_parse_version() {
        assert!(parse_version("1.0") > parse_version("0.9"));
        assert!(parse_version("2.31.0") > parse_version("2.3.0"));
        assert!(parse_version("2.10") > parse_version("2.9"));
    }

    #[test]
    fn test_parse_pkg_spec_without_version() {
        let (name, ver) = parse_pkg_spec("six");
        assert_eq!(name, "six");
        assert_eq!(ver, None);
    }

    #[test]
    fn test_parse_pkg_spec_with_version() {
        let (name, ver) = parse_pkg_spec("requests==2.31.0");
        assert_eq!(name, "requests");
        assert_eq!(ver, Some("2.31.0"));
    }

    #[test]
    fn test_parse_pkg_spec_with_version_in_name() {
        let (name, ver) = parse_pkg_spec("python-dateutil==2.8.2");
        assert_eq!(name, "python-dateutil");
        assert_eq!(ver, Some("2.8.2"));
    }

    #[test]
    fn test_find_best_wheel_version_match() {
        let info = vec![
            WheelFile {
                filename: "six-1.16.0-py2.py3-none-any.whl".into(),
                url: "https://example.com/six-1.16.0-py2.py3-none-any.whl".into(),
            },
            WheelFile {
                filename: "six-1.17.0-py2.py3-none-any.whl".into(),
                url: "https://example.com/six-1.17.0-py2.py3-none-any.whl".into(),
            },
        ];
        let w = find_best_wheel(&info, Some("1.16.0")).unwrap();
        assert!(w.filename.contains("1.16.0"));

        let w = find_best_wheel(&info, None).unwrap();
        assert!(w.filename.contains("1.17.0"));
    }

    #[test]
    fn test_find_best_wheel_py2_py3_matched() {
        let info = vec![WheelFile {
            filename: "six-1.17.0-py2.py3-none-any.whl".into(),
            url: "https://example.com/six-1.17.0.whl".into(),
        }];
        let w = find_best_wheel(&info, None).unwrap();
        assert!(w.filename.contains("six"));
    }

    #[test]
    fn test_find_best_wheel_rejects_cp_specific() {
        let info = vec![WheelFile {
            filename: "numpy-1.26.0-cp312-cp312-manylinux.whl".into(),
            url: "https://example.com/numpy.whl".into(),
        }];
        assert!(find_best_wheel(&info, None).is_none());
    }

    #[test]
    fn test_classify_single_file_package() {
        // six-like: single six.py + dist-info
        let data = make_test_wheel(&[
            ("six.py", b"def foo(): pass\n"),
            (
                "six-1.17.0.dist-info/METADATA",
                b"Name: six\nVersion: 1.17.0\n",
            ),
        ]);
        let cursor = Cursor::new(data);
        let mut archive = zip::ZipArchive::new(cursor).unwrap();
        let (is_single, root) = classify_package(&mut archive).unwrap();
        assert!(is_single, "six should be classified as single-file");
        assert_eq!(root, "six.py");
    }

    #[test]
    fn test_classify_directory_package() {
        // requests-like: directory with __init__.py
        let data = make_test_wheel(&[
            ("requests/__init__.py", b"from .api import get\n"),
            ("requests/api.py", b"def get(): pass\n"),
            ("requests-2.31.0.dist-info/METADATA", b"Name: requests\n"),
        ]);
        let cursor = Cursor::new(data);
        let mut archive = zip::ZipArchive::new(cursor).unwrap();
        let (is_single, root) = classify_package(&mut archive).unwrap();
        assert!(!is_single, "requests should be classified as directory");
        assert_eq!(root, "requests");
    }

    #[test]
    fn test_extract_single_file_wheel_vfs() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_extract_single_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();

        let data = make_test_wheel(&[
            ("six.py", b"def foo():\n    return 42\n"),
            (
                "six-1.17.0.dist-info/METADATA",
                b"Name: six\nVersion: 1.17.0\n",
            ),
        ]);
        let cursor = Cursor::new(data);
        let mut archive = zip::ZipArchive::new(cursor).unwrap();
        let (is_single, root) = classify_package(&mut archive).unwrap();
        assert!(is_single);

        extract_single_file_wheel(&mut archive, &root, "site-packages", &vfs, "/").unwrap();

        // Verify the module file was extracted
        let entries = vfs.list_dir("site-packages", "/").unwrap();
        let has_six_py = entries.iter().any(|e| e.name == "six.py");
        assert!(has_six_py, "six.py should be extracted");

        // Verify dist-info was extracted with its versioned name
        let has_dist_info = entries
            .iter()
            .any(|e| e.name == "six-1.17.0.dist-info" && e.is_dir);
        assert!(has_dist_info, "six-1.17.0.dist-info should be extracted");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_extract_directory_wheel_vfs() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_extract_dir_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();

        let data = make_test_wheel(&[
            ("requests/__init__.py", b"from .api import get\n"),
            ("requests/api.py", b"def get(): pass\n"),
            ("requests/sub/__init__.py", b"x=1\n"),
            ("requests-2.31.0.dist-info/METADATA", b"Name: requests\n"),
        ]);
        let mut cursor = Cursor::new(data);
        let mut archive = zip::ZipArchive::new(cursor).unwrap();
        extract_directory_wheel(
            &mut archive,
            "requests",
            "site-packages/requests",
            "site-packages",
            &vfs,
            "/",
        )
        .unwrap();

        let sub_entries = vfs.list_dir("site-packages/requests", "/").unwrap();
        assert!(sub_entries.iter().any(|e| e.name == "__init__.py"));
        assert!(sub_entries.iter().any(|e| e.name == "api.py"));

        // dist-info goes at site-packages top level (versioned name)
        let top_entries = vfs.list_dir("site-packages", "/").unwrap();
        assert!(
            top_entries
                .iter()
                .any(|e| e.name == "requests-2.31.0.dist-info" && e.is_dir),
            "requests-2.31.0.dist-info should be at site-packages top level"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_extract_wheel_single_file_integration() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_integrate_single_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();

        let mut cursor = Cursor::new(Vec::new());
        let mut writer = zip::ZipWriter::new(cursor);
        let opts =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
        writer.start_file("six.py", opts).unwrap();
        std::io::Write::write_all(&mut writer, b"__version__ = '1.17.0'\n").unwrap();
        writer
            .start_file("six-1.17.0.dist-info/METADATA", opts)
            .unwrap();
        std::io::Write::write_all(&mut writer, b"Name: six\n").unwrap();
        let data = writer.finish().unwrap().into_inner();

        extract_wheel(&data, "site-packages", &vfs, "/").unwrap();

        let entries = vfs.list_dir("site-packages", "/").unwrap();
        assert!(
            entries.iter().any(|e| e.name == "six.py"),
            "six.py should be there"
        );
        assert!(
            entries
                .iter()
                .any(|e| e.name == "six-1.17.0.dist-info" && e.is_dir),
            "versioned dist-info should be there"
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_extract_wheel_directory_integration() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_integrate_dir_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();

        let mut cursor = Cursor::new(Vec::new());
        let mut writer = zip::ZipWriter::new(cursor);
        let opts =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
        writer.start_file("colorama/__init__.py", opts).unwrap();
        std::io::Write::write_all(&mut writer, b"from .ansi import AnsiCodes\n").unwrap();
        writer
            .start_file("colorama-0.4.6.dist-info/METADATA", opts)
            .unwrap();
        std::io::Write::write_all(&mut writer, b"Name: colorama\n").unwrap();
        let data = writer.finish().unwrap().into_inner();

        extract_wheel(&data, "site-packages", &vfs, "/").unwrap();

        let entries = vfs.list_dir("site-packages", "/").unwrap();
        let pkg = entries
            .iter()
            .find(|e| e.name == "colorama" && e.is_dir)
            .expect("colorama directory should exist");
        assert!(pkg.is_dir);

        let sub = vfs.list_dir("site-packages/colorama", "/").unwrap();
        assert!(sub.iter().any(|e| e.name == "__init__.py"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_extract_wheel_dist_name_differs_from_module() {
        use crate::vfs::Vfs;
        // Distribution name "charset-normalizer" (hyphen) has import module
        // "charset_normalizer" (underscore). Extraction must use the module
        // dir name, not the distribution name, or Python can't import it.
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_dist_diff_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();

        let mut cursor = Cursor::new(Vec::new());
        let mut writer = zip::ZipWriter::new(cursor);
        let opts =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
        writer
            .start_file("charset_normalizer/__init__.py", opts)
            .unwrap();
        std::io::Write::write_all(&mut writer, b"__version__ = '3.5.0'\n").unwrap();
        writer
            .start_file("charset_normalizer/api.py", opts)
            .unwrap();
        std::io::Write::write_all(&mut writer, b"def from_bytes(x): pass\n").unwrap();
        writer
            .start_file("charset_normalizer-3.5.0.dist-info/METADATA", opts)
            .unwrap();
        std::io::Write::write_all(&mut writer, b"Name: charset-normalizer\n").unwrap();
        let data = writer.finish().unwrap().into_inner();

        extract_wheel(&data, "site-packages", &vfs, "/").unwrap();

        let entries = vfs.list_dir("site-packages", "/").unwrap();
        // Must be charset_normalizer (underscore), NOT charset-normalizer (hyphen)
        assert!(
            entries
                .iter()
                .any(|e| e.name == "charset_normalizer" && e.is_dir),
            "module dir should use underscore name, got: {:?}",
            entries.iter().map(|e| e.name.as_str()).collect::<Vec<_>>()
        );
        assert!(
            !entries.iter().any(|e| e.name == "charset-normalizer"),
            "hyphenated dist name should NOT be used as dir"
        );

        let sub = vfs
            .list_dir("site-packages/charset_normalizer", "/")
            .unwrap();
        assert!(sub.iter().any(|e| e.name == "__init__.py"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_pip_list_with_installed_packages() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_list_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();
        let shell = Shell::new(vfs);

        // First, empty list
        let out = shell.cmd_pip_list();
        assert!(out.stdout.contains("(no packages installed)"));

        // Create a directory-based package
        shell
            .vfs
            .create_dir_all("site-packages/colorama", "/")
            .unwrap();
        shell
            .vfs
            .write_bytes("site-packages/colorama/__init__.py", "/", b"x=1")
            .unwrap();

        let out = shell.cmd_pip_list();
        assert!(out.stdout.contains("colorama"));
        assert!(!out.stdout.contains("(no packages installed)"));
        assert_eq!(out.exit_code, 0);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_pip_list_with_single_file_module() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_list_single_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();
        let shell = Shell::new(vfs);

        // Create a single-file module with its dist-info
        shell.vfs.create_dir_all("site-packages", "/").unwrap();
        shell
            .vfs
            .write_bytes("site-packages/six.py", "/", b"x=1")
            .unwrap();
        shell
            .vfs
            .create_dir_all("site-packages/six-1.17.0.dist-info", "/")
            .unwrap();
        shell
            .vfs
            .write_bytes(
                "site-packages/six-1.17.0.dist-info/METADATA",
                "/",
                b"Name: six\nVersion: 1.17.0\n",
            )
            .unwrap();

        let out = shell.cmd_pip_list();
        assert!(
            out.stdout.contains("six"),
            "pip list should include single-file module: {}",
            out.stdout
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_pip_list_excludes_pycache() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join(format!(
            "fastshell_pip_list_pycache_{}_{}",
            std::process::id(),
            uuid::Uuid::new_v4().simple()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir.clone()).unwrap();
        let shell = Shell::new(vfs);

        // A real package + a __pycache__ dir left over from an import.
        shell
            .vfs
            .create_dir_all("site-packages/colorama", "/")
            .unwrap();
        shell
            .vfs
            .create_dir_all("site-packages/__pycache__", "/")
            .unwrap();
        shell
            .vfs
            .write_bytes("site-packages/colorama/__init__.py", "/", b"x=1")
            .unwrap();

        let out = shell.cmd_pip_list();
        assert!(out.stdout.contains("colorama"), "colorama should be listed");
        assert!(
            !out.stdout.contains("__pycache__"),
            "__pycache__ should be excluded, got: {}",
            out.stdout
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_validate_no_c_extensions() {
        let data = make_test_wheel(&[("test/__init__.py", b"x=1"), ("test/module.py", b"y=2")]);
        assert!(validate_pure_python_wheel(&data, "test").is_ok());
    }

    #[test]
    fn test_validate_rejects_so() {
        let data = make_test_wheel(&[
            ("test/__init__.py", b"x=1"),
            ("test/_speedups.so", b"\x7fELF"),
        ]);
        assert!(validate_pure_python_wheel(&data, "test").is_err());
    }

    fn make_test_wheel(files: &[(&str, &[u8])]) -> Vec<u8> {
        let cursor = Cursor::new(Vec::new());
        let mut writer = zip::ZipWriter::new(cursor);
        let options =
            zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Deflated);
        for (name, data) in files {
            writer.start_file(*name, options).unwrap();
            std::io::Write::write_all(&mut writer, data).unwrap();
        }
        writer.finish().unwrap().into_inner()
    }

    #[test]
    fn test_pip_install_help() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join("fastshell_pip_test_help");
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir).unwrap();
        let shell = Shell::new(vfs);
        let out = shell.cmd_pip_install(&["-h"]);
        assert_eq!(out.exit_code, 0);
        assert!(out.stdout.contains("pip install"));
    }

    #[test]
    fn test_pip_install_help_long() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join("fastshell_pip_test_help2");
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir).unwrap();
        let shell = Shell::new(vfs);
        let out = shell.cmd_pip_install(&["--help"]);
        assert_eq!(out.exit_code, 0);
    }

    #[test]
    fn test_pip_install_no_args_error() {
        use crate::vfs::Vfs;
        let dir = std::env::temp_dir().join("fastshell_pip_test_noargs");
        let _ = std::fs::remove_dir_all(&dir);
        let vfs = Vfs::new(dir).unwrap();
        let shell = Shell::new(vfs);
        let out = shell.cmd_pip_install(&[]);
        assert_eq!(out.exit_code, 1);
    }
}