//! §11 tail — group ROUTE templates, declarative authoring + live inheritance
//! end to end via `pic`. A group declares a `[[routes]]` template binding a
//! group-owned handler; the template is served by a **descendant** app's route
//! table (verified via `routes match`, which queries the live in-memory
//! `RouteTable`), is NOT served by a **sibling**-subtree app, `pic routes ls
//! --group` shows it, and re-apply is a NoOp.
//!
//! Nearest-wins shadowing (an app's own identical route beats the inherited
//! template) and the sibling isolation are pinned deterministically at the repo
//! layer by `manager-core/tests/group_route_templates.rs`; this journey
//! exercises the authoring + the orchestrator dispatch path the operator uses.

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
}

/// 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 {
    let ls = common::pic_as(env)
        .args(["scripts", "ls", "--group", group])
        .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!("group script `{name}` not found:\n{table}"))
}

/// `routes match` against an app — true iff a route matched the URL.
fn route_matches(env: &common::TestEnv, app: &str, url: &str) -> bool {
    let out = common::pic_as(env)
        .args(["routes", "match", "--app", app, url])
        .output()
        .expect("routes match");
    let stdout = String::from_utf8(out.stdout).unwrap();
    stdout.contains("matched") && stdout.contains("true")
}

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

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

    // A group-owned handler script the route template binds.
    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/ghello.rhai"),
        r#"log::info("group route fired"); "ok""#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/ghello.rhai"))
        .args(["--group", &group, "--name", "ghello"])
        .assert()
        .success();
    let _gs = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "ghello"),
    );

    // The group declares a route TEMPLATE binding the handler.
    let gmanifest = format!(
        "[group]\nslug = \"{group}\"\nname = \"GRoutes\"\n\n\
         [[routes]]\nscript = \"ghello\"\npath = \"/ghello\"\npath_kind = \"exact\"\n\
         host_kind = \"any\"\n"
    );
    let gpath = dir.path().join("group.toml");
    fs::write(&gpath, &gmanifest).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();

    // `routes ls --group` shows the template (path + handler).
    let ls = String::from_utf8(
        common::pic_as(&env)
            .args(["routes", "ls", "--group", &group])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        ls.contains("/ghello") && ls.contains("ghello"),
        "routes ls --group should list the template binding ghello:\n{ls}"
    );

    // Re-apply is a NoOp (the template marker already exists).
    let report = String::from_utf8(
        common::pic_as(&env)
            .args(["apply", "--file"])
            .arg(&gpath)
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        !report.contains("route")
            || report.to_lowercase().contains("no changes")
            || report.contains('0'),
        "re-apply should not create a second template:\n{report}"
    );

    // A DESCENDANT app under the group serves the inherited template.
    let blog = common::unique_slug("grt-blog");
    let _ba = AppGuard::new(&env.url, &env.token, &blog);
    common::pic_as(&env)
        .args(["apps", "create", &blog, "--group", &group])
        .assert()
        .success();
    assert!(
        route_matches(&env, &blog, "http://localhost/ghello"),
        "a descendant app must serve the inherited group route template"
    );

    // A SIBLING-subtree app (created at the instance root, not under the group)
    // must NOT serve it — the chain expansion is the isolation boundary.
    let other = common::unique_slug("grt-other");
    let _oa = AppGuard::new(&env.url, &env.token, &other);
    common::pic_as(&env)
        .args(["apps", "create", &other])
        .assert()
        .success();
    assert!(
        !route_matches(&env, &other, "http://localhost/ghello"),
        "a sibling-subtree app must NOT serve another subtree's route template"
    );
}
