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

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

const STANDARD_VEC_I64_SOURCE_FACADE_ALPHA: &[&str] = &[
    "empty",
    "append",
    "len",
    "at",
    "singleton",
    "append2",
    "append3",
    "pair",
    "triple",
    "is_empty",
    "index_or",
    "first_or",
    "last_or",
    "index_option",
    "first_option",
    "last_option",
    "index_of_option",
    "last_index_of_option",
    "contains",
    "count_of",
    "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_i64_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_i64");
    let slovo_vec_i64 = compiler_root.join("../lib/std/vec_i64.slo");

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

    let slovo_source = read(&slovo_vec_i64);
    assert!(
        slovo_source.starts_with("(module vec_i64 (export "),
        "repo-root Slovo std/vec_i64.slo must export imported helpers directly"
    );
    assert!(
        !slovo_source.contains("capacity")
            && !slovo_source.contains("reserve")
            && !slovo_source.contains("shrink")
            && !slovo_source.contains("sort")
            && !slovo_source.contains("map")
            && !slovo_source.contains("filter")
            && !slovo_source.contains("(vec i32)")
            && !slovo_source.contains("(vec f64)")
            && !slovo_source.contains("(vec string)")
            && !slovo_source.contains("(vec bool)")
            && !slovo_source.contains("(option f64)")
            && !slovo_source.contains("(option string)")
            && !slovo_source.contains("(option bool)")
            && !slovo_source.contains("(result i32")
            && !slovo_source.contains("(result i64")
            && !slovo_source.contains("(result f64")
            && !slovo_source.contains("(result string")
            && !slovo_source.contains("(result bool"),
        "std/vec_i64.slo must stay narrow and explicit"
    );
    for helper in STANDARD_VEC_I64_SOURCE_FACADE_ALPHA {
        assert!(
            slovo_source.contains(&format!("(fn {} ", helper)),
            "Slovo std/vec_i64.slo is missing helper `{}`",
            helper
        );
        assert!(
            main.contains(helper),
            "std-import-vec_i64 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_i64 facade source search fmt --check", &fmt);

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

    let test = run_glagol([OsStr::new("test"), project.as_os_str()]);
    assert_success_stdout(
        test,
        EXPECTED_STD_VEC_I64_OUTPUT,
        "std vec_i64 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);
}
