//! §5.5 opt-in extension points, end to end via `pic`:
//!   * a group marks a module `theme` an extension point (default body) and an
//!     endpoint `render` imports it; an app inherits → uses the DEFAULT,
//!   * the app provides its OWN `theme` module → `render` now binds the app's
//!     (DYNAMIC override — the inverse of the Phase 4b sealed/lexical import),
//!   * `pic extension-points ls --app` shows the resolved provider,
//!   * an inherited extension point with NO provider is a `pic 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 extension_point_default_then_app_override() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("ep-grp");
    let child = common::unique_slug("ep-child");

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

    let dir = manifest_dir();
    // Group default `theme` module + a `render` endpoint importing it.
    fs::write(
        dir.path().join("scripts/theme.rhai"),
        r#"fn color() { "blue" }"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/theme.rhai"))
        .args(["--group", &group, "--name", "theme", "--kind", "module"])
        .assert()
        .success();
    fs::write(
        dir.path().join("scripts/render.rhai"),
        r#"import "theme" as t; t::color()"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/render.rhai"))
        .args(["--group", &group, "--name", "render"])
        .assert()
        .success();
    let _gt = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "theme"),
    );
    let _gr = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "render"),
    );

    // Mark `theme` an extension point at the group (declarative apply).
    let gmanifest =
        format!("[group]\nslug = \"{group}\"\nname = \"EP\"\n\nextension_points = [\"theme\"]\n");
    let gpath = dir.path().join("group.toml");
    fs::write(&gpath, &gmanifest).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();

    // App under the group; a `caller` invokes the inherited `render`.
    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("render", #{})"#,
    )
    .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");

    // Default: with no app override, `render`'s EP import falls back to the
    // group's default body → "blue".
    assert_eq!(
        invoke_body(&env, &caller_id),
        serde_json::json!("blue"),
        "an inherited extension point resolves the group's default body"
    );

    // DYNAMIC OVERRIDE: the app provides its own `theme`. Because `theme` is an
    // extension point, the group endpoint's import now binds the APP's module —
    // the exact inverse of a Phase 4b lexical (sealed) import.
    fs::write(
        dir.path().join("scripts/apptheme.rhai"),
        r#"fn color() { "red" }"#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/apptheme.rhai"))
        .args(["--app", &child, "--name", "theme", "--kind", "module"])
        .assert()
        .success();
    assert_eq!(
        invoke_body(&env, &caller_id),
        serde_json::json!("red"),
        "the app must override an extension point the group declared"
    );

    // `extension-points ls --app` shows the resolved provider.
    let ls = String::from_utf8(
        common::pic_as(&env)
            .args(["extension-points", "ls", "--app", &child])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        ls.contains("theme") && ls.contains("app override"),
        "ls should report the app override:\n{ls}"
    );
}

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

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

    // Group declares an EP `ghost` with NO default body (body-less).
    let dir = manifest_dir();
    let gmanifest =
        format!("[group]\nslug = \"{group}\"\nname = \"EPN\"\n\nextension_points = [\"ghost\"]\n");
    let gpath = dir.path().join("group.toml");
    fs::write(&gpath, &gmanifest).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();

    // App under the group provides no `ghost` → any plan for it is refused.
    let _child = AppGuard::new(&env.url, &env.token, &child);
    common::pic_as(&env)
        .args(["apps", "create", &child, "--group", &group])
        .assert()
        .success();
    let amanifest = format!("[app]\nslug = \"{child}\"\nname = \"EPN child\"\n");
    let apath = dir.path().join("picloud.toml");
    fs::write(&apath, &amanifest).unwrap();
    let out = common::pic_as(&env)
        .args(["plan", "--file"])
        .arg(&apath)
        .output()
        .expect("plan");
    assert!(
        !out.status.success(),
        "an inherited extension point with no provider must fail plan"
    );
    let stderr = String::from_utf8_lossy(&out.stderr).to_lowercase();
    assert!(
        stderr.contains("ghost") || stderr.contains("no provider") || stderr.contains("extension"),
        "plan error should name the unprovided extension point:\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)
}

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();
    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")
}
