use std::{
    ffi::OsStr,
    fs,
    path::Path,
    process::{Command, Output},
};

const EXPECTED_STD_VEC_I32_OUTPUT: &str = concat!(
    "test \"explicit std vec_i32 empty len facade\" ... ok\n",
    "test \"explicit std vec_i32 direct at facade\" ... ok\n",
    "test \"explicit std vec_i32 builder helpers\" ... ok\n",
    "test \"explicit std vec_i32 constructor helpers\" ... ok\n",
    "test \"explicit std vec_i32 range helper\" ... ok\n",
    "test \"explicit std vec_i32 query helpers\" ... ok\n",
    "test \"explicit std vec_i32 option query helpers\" ... ok\n",
    "test \"explicit std vec_i32 starts_with helper\" ... ok\n",
    "test \"explicit std vec_i32 ends_with helper\" ... ok\n",
    "test \"explicit std vec_i32 without_suffix helper\" ... ok\n",
    "test \"explicit std vec_i32 without_prefix helper\" ... ok\n",
    "test \"explicit std vec_i32 transform helpers\" ... ok\n",
    "test \"explicit std vec_i32 subvec helper\" ... ok\n",
    "test \"explicit std vec_i32 insert helper\" ... ok\n",
    "test \"explicit std vec_i32 insert range helper\" ... ok\n",
    "test \"explicit std vec_i32 replace helper\" ... ok\n",
    "test \"explicit std vec_i32 replace range helper\" ... ok\n",
    "test \"explicit std vec_i32 remove helper\" ... ok\n",
    "test \"explicit std vec_i32 remove range helper\" ... ok\n",
    "test \"explicit std vec_i32 count_of helper\" ... ok\n",
    "test \"explicit std vec_i32 real program helpers\" ... ok\n",
    "test \"explicit std vec_i32 helpers all\" ... ok\n",
    "22 test(s) passed\n",
);

const STANDARD_VEC_I32_SOURCE_FACADE_ALPHA: &[&str] = &[
    "empty",
    "append",
    "len",
    "at",
    "singleton",
    "append2",
    "append3",
    "pair",
    "triple",
    "repeat",
    "range",
    "range_from_zero",
    "is_empty",
    "index_or",
    "first_or",
    "last_or",
    "index_option",
    "first_option",
    "last_option",
    "index_of_option",
    "last_index_of_option",
    "count_of",
    "contains",
    "sum",
    "concat",
    "take",
    "starts_with",
    "without_prefix",
    "ends_with",
    "without_suffix",
    "drop",
    "reverse",
    "subvec",
    "insert_at",
    "insert_range",
    "replace_at",
    "replace_range",
    "remove_at",
    "remove_range",
];

#[test]
fn explicit_std_vec_i32_import_loads_repo_root_standard_source() {
    let compiler_root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let project = compiler_root.join("../examples/projects/std-import-vec_i32");
    let slovo_vec_i32 = compiler_root.join("../lib/std/vec_i32.slo");

    assert!(
        !project.join("src/vec_i32.slo").exists(),
        "std-import-vec_i32 must not carry a local vec_i32 module copy"
    );
    let main = read(&project.join("src/main.slo"));
    assert!(
        main.starts_with("(module main)\n\n(import std.vec_i32 ("),
        "std-import-vec_i32 must exercise explicit `std.vec_i32` import syntax"
    );

    let slovo_source = read(&slovo_vec_i32);
    assert!(
        slovo_source.starts_with("(module vec_i32 (export "),
        "repo-root Slovo std/vec_i32.slo must export imported helpers directly"
    );
    for helper in STANDARD_VEC_I32_SOURCE_FACADE_ALPHA {
        assert!(
            slovo_source.contains(&format!("(fn {} ", helper)),
            "Slovo std/vec_i32.slo is missing helper `{}`",
            helper
        );
        assert!(
            main.contains(helper),
            "std-import-vec_i32 main fixture import/use is missing helper `{}`",
            helper
        );
    }

    let fmt = run_glagol([
        OsStr::new("fmt"),
        OsStr::new("--check"),
        project.as_os_str(),
    ]);
    assert_success("std vec_i32 facade source search fmt --check", &fmt);

    let check = run_glagol([OsStr::new("check"), project.as_os_str()]);
    assert_success_stdout(check, "", "std vec_i32 facade source search check");

    let test = run_glagol([OsStr::new("test"), project.as_os_str()]);
    assert_success_stdout(
        test,
        EXPECTED_STD_VEC_I32_OUTPUT,
        "std vec_i32 facade source search test",
    );
}

fn run_glagol<I, S>(args: I) -> Output
where
    I: IntoIterator<Item = S>,
    S: AsRef<std::ffi::OsStr>,
{
    Command::new(env!("CARGO_BIN_EXE_glagol"))
        .args(args)
        .current_dir(Path::new(env!("CARGO_MANIFEST_DIR")))
        .output()
        .expect("run glagol")
}

fn read(path: &Path) -> String {
    fs::read_to_string(path).unwrap_or_else(|err| panic!("read `{}`: {}", path.display(), err))
}

fn assert_success(context: &str, output: &Output) {
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        output.status.success(),
        "{} failed\nstatus: {:?}\nstdout:\n{}\nstderr:\n{}",
        context,
        output.status.code(),
        stdout,
        stderr
    );
}

fn assert_success_stdout(output: Output, expected: &str, context: &str) {
    assert_success(context, &output);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout, expected, "{}", context);
}
