//! prep.3 (kernel-extension-mechanics): workspace-load tests for
//! kernel-tier auto-import. These tests exercise the flag-driven
//! generalisation of the prior hardcoded `&["prelude"]` literal —
//! every workspace-loaded module with `kernel: true` joins the
//! implicit-imports list and therefore makes its types visible bare
//! to every consumer, even consumers that did not name it under
//! `(import …)`.
//!
//! Reachability: a user `(kernel)` module enters the workspace's
//! modules map only if some module in the import chain reaches it
//! (the standard import-graph DFS). The kernel-tier flag does NOT
//! cause unreachable `.ail` files in the entry's directory to be
//! loaded — see Concern in the iter prep.3 end-report. The
//! built-in `prelude` and `raw_buf` are always loaded because
//! the loader injects them programmatically; user kernel-tier
//! modules need a path from the entry.

use ailang_surface::load_workspace;
use std::path::{Path, PathBuf};

/// Write a Form-A source file into the temp dir and return its path.
fn write_module(dir: &Path, name: &str, src: &str) -> PathBuf {
    let path = dir.join(format!("{name}.ail"));
    std::fs::write(&path, src).expect("write fixture");
    path
}

/// prep.3: a workspace-loaded `(kernel)` module makes its types
/// visible bare to consumers that did NOT name it under
/// `(import …)`. Property: the kernel-flag filter derives the
/// implicit-imports list from every `kernel: true` module in the
/// modules map — `consumer` references `KT` bare and validates
/// because `bridge` brought `k_mod` into the workspace.
#[test]
fn kernel_tier_module_auto_imports_without_explicit_import() {
    let dir = tempfile::tempdir().expect("tempdir");
    // k_mod carries (kernel) and declares KT.
    write_module(
        dir.path(),
        "k_mod",
        "(module k_mod\n  (kernel)\n  (data KT (vars a) (ctor KCtor a)))\n",
    );
    // bridge imports k_mod so it enters the workspace.
    write_module(
        dir.path(),
        "bridge",
        concat!(
            "(module bridge\n",
            "  (import k_mod)\n",
            "  (fn anchor\n",
            "    (type (forall (vars a) (fn-type (params (own (con KT a))) (ret (own (con Unit))))))\n",
            "    (params k) (body unit)))\n",
        ),
    );
    // The entry imports bridge (transitively pulling k_mod), and
    // uses `(con KT (var a))` bare — no explicit import of k_mod.
    let entry = write_module(
        dir.path(),
        "consumer",
        concat!(
            "(module consumer\n",
            "  (import bridge)\n",
            "  (fn use_kt\n",
            "    (type (forall (vars a) (fn-type (params (own (con KT a))) (ret (own (con Unit))))))\n",
            "    (params k) (body unit)))\n",
        ),
    );

    let ws = load_workspace(&entry).expect("workspace loads (kernel-tier auto-import)");
    assert!(
        ws.modules.contains_key("k_mod"),
        "k_mod was loaded transitively via bridge"
    );
    assert!(
        ws.modules.get("k_mod").unwrap().kernel,
        "k_mod is marked kernel-tier"
    );
}

/// prep.3: two `(kernel)` modules co-load without conflict; both
/// enter the implicit-imports list and both are visible to a
/// consumer that imported neither directly. Property: the filter
/// `modules.values().filter(|m| m.kernel)` walks ALL modules (not
/// just the first match), so every kernel-tier module gets
/// auto-imported.
#[test]
fn two_kernel_tier_modules_coload() {
    let dir = tempfile::tempdir().expect("tempdir");
    write_module(
        dir.path(),
        "k_a",
        "(module k_a\n  (kernel)\n  (data A (ctor AC)))\n",
    );
    write_module(
        dir.path(),
        "k_b",
        "(module k_b\n  (kernel)\n  (data B (ctor BC)))\n",
    );
    // bridge imports both kernel modules; consumer transitively
    // sees both via the kernel-flag filter without explicit import.
    write_module(
        dir.path(),
        "bridge",
        concat!(
            "(module bridge\n",
            "  (import k_a)\n",
            "  (import k_b)\n",
            "  (fn anchor\n",
            "    (type (fn-type (params (own (con A)) (own (con B))) (ret (own (con Unit)))))\n",
            "    (params a b) (body unit)))\n",
        ),
    );
    let entry = write_module(
        dir.path(),
        "consumer",
        concat!(
            "(module consumer\n",
            "  (import bridge)\n",
            "  (fn use_ab\n",
            "    (type (fn-type (params (own (con A)) (own (con B))) (ret (own (con Unit)))))\n",
            "    (params a b) (body unit)))\n",
        ),
    );

    let ws = load_workspace(&entry).expect("workspace with two kernel modules");
    assert!(ws.modules.contains_key("k_a"));
    assert!(ws.modules.contains_key("k_b"));
    assert!(ws.modules.get("k_a").unwrap().kernel);
    assert!(ws.modules.get("k_b").unwrap().kernel);
}

/// prep.3: an explicit `(import …)` for a kernel-tier module
/// coexists with the auto-import — no double-resolution error, no
/// behaviour drift. Property: the implicit-imports list and the
/// explicit-imports list are both consulted by the validator;
/// having the same name in both does not produce a duplicate-
/// import diagnostic.
#[test]
fn explicit_import_takes_precedence_over_auto_import() {
    let dir = tempfile::tempdir().expect("tempdir");
    write_module(
        dir.path(),
        "k_mod",
        "(module k_mod\n  (kernel)\n  (data KT (ctor KC)))\n",
    );
    // consumer explicitly imports k_mod AND uses KT bare.
    let entry = write_module(
        dir.path(),
        "consumer",
        concat!(
            "(module consumer\n",
            "  (import k_mod)\n",
            "  (fn use_kt\n",
            "    (type (fn-type (params (own (con KT))) (ret (own (con Unit)))))\n",
            "    (params k) (body unit)))\n",
        ),
    );

    let ws = load_workspace(&entry).expect("explicit + auto coexist");
    assert!(ws.modules.contains_key("k_mod"));
    assert!(ws.modules.get("k_mod").unwrap().kernel);
}
