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

const EXPECTED_TEST_OUTPUT: &str = concat!(
    "test \"explicit local time monotonic facade\" ... ok\n",
    "test \"explicit local time sleep zero facade\" ... ok\n",
    "test \"explicit local time facade all\" ... ok\n",
    "3 test(s) passed\n",
);

const STANDARD_TIME_SOURCE_FACADE_ALPHA: &[&str] = &["monotonic_ms", "sleep_ms_zero"];

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

    assert_local_time_fixture_is_source_authored(&project);

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

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

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

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

    assert!(
        time.starts_with("(module time (export "),
        "time.slo must stay an explicit local module export"
    );
    assert!(
        main.starts_with("(module main)\n\n(import time ("),
        "main.slo must stay an explicit local time import"
    );
    assert!(
        !main.contains("(import std") && !main.contains("(import slovo.std"),
        "exp-37 fixture must not depend on automatic or package std imports"
    );
    assert!(
        time.contains("(std.time.monotonic_ms)") && time.contains("(std.time.sleep_ms 0)"),
        "time.slo must use only the existing promoted std.time source calls"
    );
    let mut non_time_std = time.clone();
    for allowed in ["std.time.monotonic_ms", "std.time.sleep_ms"] {
        non_time_std = non_time_std.replace(allowed, "");
    }
    assert!(
        !non_time_std.contains("std.") && !main.contains("std."),
        "exp-37 fixture must not introduce other compiler-known std names"
    );
    assert!(
        !time.contains("std.time.now")
            && !time.contains("calendar")
            && !time.contains("timezone")
            && !time.contains("async")
            && !time.contains("cancel")
            && !time.contains("schedule"),
        "exp-37 fixture must not claim deferred time APIs or scheduling semantics"
    );
    assert!(
        time.contains("(fn sleep_ms_zero () -> i32\n  (std.time.sleep_ms 0)\n  0)"),
        "sleep_ms_zero must return 0 after calling the unit-return sleep facade"
    );

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