//! Phase 4b group-owned modules + the lexical import resolver (§5.5), e2e via `pic`:
//!   * a group owns a `module` and an endpoint that imports it; an app under the
//!     group inherits the endpoint and resolves the module down the chain,
//!   * **trust boundary** — the inheriting app defines a same-named module of
//!     its own; the inherited group endpoint's import must STILL bind the
//!     group's module (a leaf cannot shadow it),
//!   * **CoW / app origin** — an app-owned endpoint importing that name resolves
//!     the app's module,
//!   * a manifest whose script imports a non-existent module is a `plan` error.

use std::fs;

use tempfile::TempDir;

use crate::common;
use crate::common::cleanup::{AppGuard, GroupGuard, ScriptGuard};

fn manifest_dir() -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    fs::create_dir_all(dir.path().join("scripts")).expect("scripts dir");
    dir
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn group_module_is_lexically_sealed_under_inheritance() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("gm-grp");
    let child = common::unique_slug("gm-child");

    // GroupGuard first so it drops LAST — after the app + group scripts.
    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    let dir = manifest_dir();

    // Group module `util` and a group endpoint `welcome` that imports it.
    fs::write(
        dir.path().join("scripts/util.rhai"),
        r#"fn greet(n) { "group:" + n }"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/util.rhai"))
        .args(["--group", &group, "--name", "util", "--kind", "module"])
        .assert()
        .success();

    fs::write(
        dir.path().join("scripts/welcome.rhai"),
        r#"import "util" as u; u::greet("x")"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/welcome.rhai"))
        .args(["--group", &group, "--name", "welcome"])
        .assert()
        .success();
    // Group scripts block group deletion (ON DELETE RESTRICT) — guard both.
    let _gu = ScriptGuard::new(&env.url, &env.token, &group_script_id(&env, &group, "util"));
    let _gw = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "welcome"),
    );

    // App under the group; a `caller` invokes the inherited `welcome`.
    let _child = AppGuard::new(&env.url, &env.token, &child);
    common::pic_as(&env)
        .args(["apps", "create", &child, "--group", &group])
        .assert()
        .success();
    fs::write(
        dir.path().join("scripts/caller.rhai"),
        r#"invoke("welcome", #{})"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/caller.rhai"))
        .args(["--app", &child, "--name", "caller"])
        .assert()
        .success();
    let caller_id = app_script_id(&env, &child, "caller");

    // Inheritance: welcome resolves `util` from the group → "group:x".
    assert_eq!(
        invoke_body(&env, &caller_id),
        serde_json::json!("group:x"),
        "inherited endpoint must resolve the group's module"
    );

    // TRUST BOUNDARY: the app defines its OWN `util` module. The group
    // endpoint's import must STILL bind the GROUP's util (sealed from below).
    fs::write(
        dir.path().join("scripts/apputil.rhai"),
        r#"fn greet(n) { "app:" + n }"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/apputil.rhai"))
        .args(["--app", &child, "--name", "util", "--kind", "module"])
        .assert()
        .success();
    assert_eq!(
        invoke_body(&env, &caller_id),
        serde_json::json!("group:x"),
        "a leaf's same-named module must NOT shadow an inherited group endpoint's import"
    );

    // CoW / app origin: an app-owned endpoint importing `util` gets the APP's.
    fs::write(
        dir.path().join("scripts/appcaller.rhai"),
        r#"import "util" as u; u::greet("y")"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/appcaller.rhai"))
        .args(["--app", &child, "--name", "appcaller"])
        .assert()
        .success();
    let appcaller_id = app_script_id(&env, &child, "appcaller");
    assert_eq!(
        invoke_body(&env, &appcaller_id),
        serde_json::json!("app:y"),
        "an app-owned script's import must resolve the app's own module"
    );
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn reserved_group_module_name_is_rejected() {
    // Parity with app modules (api.rs): a group `module` named after a built-in
    // SDK namespace is refused at create — not silently accepted to fail later.
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("gm-rsv");

    let _g = GroupGuard::new(&env.url, &env.token, &group);
    common::pic_as(&env)
        .args(["groups", "create", &group])
        .assert()
        .success();

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/kv.rhai"), r#"fn x() { 1 }"#).unwrap();
    let out = common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/kv.rhai"))
        .args(["--group", &group, "--name", "kv", "--kind", "module"])
        .output()
        .expect("deploy");
    assert!(
        !out.status.success(),
        "a reserved module name must be rejected for a group module too"
    );
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn dangling_import_is_rejected_by_plan() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let app = common::unique_slug("gm-dangle");

    let _app = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app])
        .assert()
        .success();

    // A manifest whose endpoint imports a module that exists nowhere on the
    // chain. `pic plan` must refuse it (the §5.5 dangling-import check) rather
    // than apply a script that 404s its import at runtime.
    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/broken.rhai"),
        r#"import "ghost" as g; g::run()"#,
    )
    .unwrap();
    let manifest = format!(
        "[app]\nslug = \"{app}\"\nname = \"Dangle\"\n\n\
         [[scripts]]\nname = \"broken\"\nfile = \"scripts/broken.rhai\"\n"
    );
    let manifest_path = dir.path().join("picloud.toml");
    fs::write(&manifest_path, &manifest).unwrap();

    let out = common::pic_as(&env)
        .args(["plan", "--file"])
        .arg(&manifest_path)
        .output()
        .expect("plan");
    assert!(!out.status.success(), "plan must reject a dangling import");
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    assert!(
        stderr.contains("ghost") || stderr.contains("unknown module") || stderr.contains("import"),
        "plan error should name the missing module:\n{stderr}"
    );
}

/// Id of the named script in a group (`pic scripts ls --group <g>`).
fn group_script_id(env: &common::TestEnv, group: &str, name: &str) -> String {
    named_id(env, &["scripts", "ls", "--group", group], name)
}

/// Id of the named script in an app (`pic scripts ls --app <a>`).
fn app_script_id(env: &common::TestEnv, app: &str, name: &str) -> String {
    named_id(env, &["scripts", "ls", "--app", app], name)
}

/// Run a `scripts ls` and pick the id of the row whose name column matches.
fn named_id(env: &common::TestEnv, args: &[&str], name: &str) -> String {
    let ls = common::pic_as(env).args(args).output().expect("scripts ls");
    let table = String::from_utf8(ls.stdout).unwrap();
    // Rows are `id\t<owner_slug>\tname\tversion\tupdated_at`.
    table
        .lines()
        .map(common::cells)
        .find(|c| c.get(2) == Some(&name))
        .and_then(|c| c.first().map(|s| (*s).to_string()))
        .unwrap_or_else(|| panic!("script `{name}` not found:\n{table}"))
}

fn invoke_body(env: &common::TestEnv, id: &str) -> serde_json::Value {
    let out = common::pic_as(env)
        .args(["scripts", "invoke", id])
        .output()
        .expect("scripts invoke");
    assert!(
        out.status.success(),
        "invoke failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    serde_json::from_slice(&out.stdout).expect("invoke body is JSON")
}
