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

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

const STANDARD_VEC_STRING_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",
    "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 standard_vec_string_source_helper_project_checks_formats_and_tests() {
    let project = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../examples/projects/std-layout-local-vec_string");

    assert_local_vec_string_fixture_is_source_authored(&project);

    let fmt = run_glagol([
        OsStr::new("fmt"),
        OsStr::new("--check"),
        project.as_os_str(),
    ]);
    assert_success("std layout local vec_string fmt --check", &fmt);

    let check = run_glagol([OsStr::new("check"), project.as_os_str()]);
    assert_success_stdout(check, "", "std layout local vec_string check");

    let test = run_glagol([OsStr::new("test"), project.as_os_str()]);
    assert_success_stdout(
        test,
        EXPECTED_TEST_OUTPUT,
        "std layout local vec_string test output",
    );
}

fn assert_local_vec_string_fixture_is_source_authored(project: &Path) {
    let vec_string = read(&project.join("src/vec_string.slo"));
    let main = read(&project.join("src/main.slo"));

    assert!(
        vec_string.starts_with("(module vec_string (export "),
        "vec_string.slo must stay an explicit local module export"
    );
    assert!(
        main.starts_with("(module main)\n\n(import vec_string ("),
        "main.slo must stay an explicit local vec_string import"
    );
    assert!(
        !vec_string.contains("(import std")
            && !main.contains("(import std.")
            && !vec_string.contains("(import slovo.std")
            && !main.contains("(import slovo.std"),
        "vec_string fixture must not depend on automatic or package std imports"
    );
    assert!(
        !vec_string.contains("(var ")
            && !main.contains("(var ")
            && !vec_string.contains("(set ")
            && !main.contains("(set "),
        "vec_string fixture must stay recursive and immutable without mutating locals"
    );
    assert!(
        !vec_string.contains("(vec i32)")
            && !main.contains("(vec i32)")
            && !vec_string.contains("(vec i64)")
            && !main.contains("(vec i64)")
            && !vec_string.contains("(vec f64)")
            && !main.contains("(vec f64)")
            && !vec_string.contains("(vec bool)")
            && !main.contains("(vec bool)")
            && !vec_string.contains("(option i64)")
            && !main.contains("(option i64)")
            && !vec_string.contains("(option f64)")
            && !main.contains("(option f64)")
            && !vec_string.contains("(option bool)")
            && !main.contains("(option bool)")
            && !vec_string.contains("(result i32")
            && !main.contains("(result i32")
            && !vec_string.contains("(result i64")
            && !main.contains("(result i64")
            && !vec_string.contains("(result f64")
            && !main.contains("(result f64")
            && !vec_string.contains("(result string")
            && !main.contains("(result string")
            && !vec_string.contains("(result bool")
            && !main.contains("(result bool"),
        "vec_string fixture must stay limited to concrete vec string plus option i32/string helpers"
    );

    let mut non_vec_std = vec_string.clone();
    for allowed in [
        "std.vec.string.empty",
        "std.vec.string.append",
        "std.vec.string.len",
        "std.vec.string.index",
    ] {
        non_vec_std = non_vec_std.replace(allowed, "");
    }
    assert!(
        !non_vec_std.contains("std.") && !main.contains("std."),
        "vec_string fixture must use only the promoted std.vec.string runtime names"
    );
    assert!(
        !vec_string.contains("capacity")
            && !vec_string.contains("reserve")
            && !vec_string.contains("shrink")
            && !vec_string.contains("sort")
            && !vec_string.contains("map")
            && !vec_string.contains("filter")
            && !vec_string.contains("concat_all"),
        "vec_string fixture must not claim deferred generic or mutation-heavy collection APIs"
    );

    for helper in STANDARD_VEC_STRING_SOURCE_FACADE_ALPHA {
        assert!(
            vec_string.contains(&format!("(fn {} ", helper)),
            "vec_string.slo is missing source helper `{}`",
            helper
        );
        assert!(
            main.contains(helper),
            "main.slo does not explicitly import/use `{}`",
            helper
        );
    }
    for helper in [
        "index_of_option_loop",
        "last_index_of_option_loop",
        "contains_loop",
        "count_of_loop",
        "concat_loop",
        "take_loop",
        "drop_loop",
        "reverse_loop",
    ] {
        assert!(
            vec_string.contains(&format!("(fn {} ", helper)),
            "vec_string.slo is missing recursive source helper `{}`",
            helper
        );
    }
}

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\nstdout:\n{}\nstderr:\n{}",
        context,
        stdout,
        stderr
    );
    assert!(stderr.is_empty(), "{} wrote stderr:\n{}", context, stderr);
}

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

    assert!(
        output.status.success(),
        "{} failed\nstdout:\n{}\nstderr:\n{}",
        context,
        stdout,
        stderr
    );
    assert_eq!(stdout, expected, "{} stdout drifted", context);
    assert!(stderr.is_empty(), "{} wrote stderr:\n{}", context, stderr);
}
