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

const EXPECTED_TEST_OUTPUT: &str = concat!(
    "test \"explicit local option i32 observation\" ... ok\n",
    "test \"explicit local option i32 unwrap_some\" ... ok\n",
    "test \"explicit local option i32 unwrap_or\" ... ok\n",
    "test \"explicit local option i32 some_or_err ok\" ... ok\n",
    "test \"explicit local option i32 some_or_err err\" ... ok\n",
    "test \"explicit local option u32 observation\" ... ok\n",
    "test \"explicit local option u32 unwrap_some\" ... ok\n",
    "test \"explicit local option u32 unwrap_or\" ... ok\n",
    "test \"explicit local option u32 some_or_err ok\" ... ok\n",
    "test \"explicit local option u32 some_or_err err\" ... ok\n",
    "test \"explicit local option i64 observation\" ... ok\n",
    "test \"explicit local option i64 unwrap_some\" ... ok\n",
    "test \"explicit local option i64 unwrap_or\" ... ok\n",
    "test \"explicit local option i64 some_or_err ok\" ... ok\n",
    "test \"explicit local option i64 some_or_err err\" ... ok\n",
    "test \"explicit local option u64 observation\" ... ok\n",
    "test \"explicit local option u64 unwrap_some\" ... ok\n",
    "test \"explicit local option u64 unwrap_or\" ... ok\n",
    "test \"explicit local option u64 some_or_err ok\" ... ok\n",
    "test \"explicit local option u64 some_or_err err\" ... ok\n",
    "test \"explicit local option f64 observation\" ... ok\n",
    "test \"explicit local option f64 unwrap_some\" ... ok\n",
    "test \"explicit local option f64 unwrap_or\" ... ok\n",
    "test \"explicit local option f64 some_or_err ok\" ... ok\n",
    "test \"explicit local option f64 some_or_err err\" ... ok\n",
    "test \"explicit local option bool observation\" ... ok\n",
    "test \"explicit local option bool unwrap_some\" ... ok\n",
    "test \"explicit local option bool unwrap_or\" ... ok\n",
    "test \"explicit local option bool some_or_err ok\" ... ok\n",
    "test \"explicit local option bool some_or_err err\" ... ok\n",
    "test \"explicit local option string observation\" ... ok\n",
    "test \"explicit local option string unwrap_some\" ... ok\n",
    "test \"explicit local option string unwrap_or\" ... ok\n",
    "test \"explicit local option string some_or_err ok\" ... ok\n",
    "test \"explicit local option string some_or_err err\" ... ok\n",
    "test \"explicit local option helpers all\" ... ok\n",
    "36 test(s) passed\n",
);

const STANDARD_OPTION_SOURCE_HELPERS_ALPHA: &[&str] = &[
    "some_i32",
    "none_i32",
    "is_some_i32",
    "is_none_i32",
    "unwrap_some_i32",
    "unwrap_or_i32",
    "some_u32",
    "none_u32",
    "is_some_u32",
    "is_none_u32",
    "unwrap_some_u32",
    "unwrap_or_u32",
    "some_i64",
    "none_i64",
    "is_some_i64",
    "is_none_i64",
    "unwrap_some_i64",
    "unwrap_or_i64",
    "some_u64",
    "none_u64",
    "is_some_u64",
    "is_none_u64",
    "unwrap_some_u64",
    "unwrap_or_u64",
    "some_f64",
    "none_f64",
    "is_some_f64",
    "is_none_f64",
    "unwrap_some_f64",
    "unwrap_or_f64",
    "some_bool",
    "none_bool",
    "is_some_bool",
    "is_none_bool",
    "unwrap_some_bool",
    "unwrap_or_bool",
    "some_string",
    "none_string",
    "is_some_string",
    "is_none_string",
    "unwrap_some_string",
    "unwrap_or_string",
];

const STANDARD_OPTION_RESULT_BRIDGE_HELPERS_ALPHA: &[&str] = &[
    "some_or_err_i32",
    "some_or_err_u32",
    "some_or_err_i64",
    "some_or_err_u64",
    "some_or_err_f64",
    "some_or_err_bool",
    "some_or_err_string",
];

#[test]
fn standard_option_source_helper_project_checks_formats_and_tests() {
    let project =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/projects/std-layout-local-option");

    assert_local_option_fixture_is_source_authored(&project);

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

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

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

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

    assert!(
        option.starts_with("(module option (export "),
        "option.slo must stay an explicit local module export"
    );
    assert!(
        main.starts_with("(module main)\n\n(import option ("),
        "main.slo must stay an explicit local option import"
    );
    assert!(
        !option.contains("std.") && !main.contains("std."),
        "exp-36 fixture must not use compiler-known std runtime names"
    );
    assert!(
        !main.contains("(import std") && !main.contains("(import slovo.std"),
        "exp-36 fixture must not depend on automatic or package std imports"
    );
    assert!(
        !option.contains("std.result.")
            && !main.contains("std.result.")
            && !main.contains("(import result"),
        "exp-109 fixture must bridge through raw concrete result forms, not compiler-known std.result names or a separate local result module"
    );

    for helper in STANDARD_OPTION_SOURCE_HELPERS_ALPHA {
        assert!(
            option.contains(&format!("(fn {} ", helper)),
            "option.slo is missing source helper `{}`",
            helper
        );
        assert!(
            main.contains(helper),
            "main.slo does not explicitly import/use `{}`",
            helper
        );
    }

    for helper in STANDARD_OPTION_RESULT_BRIDGE_HELPERS_ALPHA {
        assert!(
            option.contains(&format!("(fn {} ", helper)),
            "option.slo is missing bridge helper `{}`",
            helper
        );
        assert!(
            main.contains(helper),
            "main.slo does not explicitly import/use bridge 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);
}
