//! §4.5 M5 — stateful (cron/queue) group trigger templates, declarative end to
//! end via `pic`. A group declares a cron template; applying it and creating a
//! descendant app materializes a per-app cron copy (visible in `pic triggers ls
//! --app`). The reconcile mechanism itself (per-app copy, idempotent,
//! de-materialize on reparent, queue slot-conflict warning) is pinned
//! deterministically by `manager-core/tests/stateful_templates.rs`; this journey
//! exercises the CLI authoring plus the apply and app-create hooks.

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
}

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

/// Count rows of `kind` in `pic triggers ls --app`.
fn app_trigger_count(env: &common::TestEnv, app: &str, kind: &str) -> usize {
    let out = common::pic_as(env)
        .args(["triggers", "ls", "--app", app])
        .output()
        .expect("triggers ls");
    String::from_utf8(out.stdout)
        .unwrap()
        .lines()
        .map(common::cells)
        .filter(|c| c.contains(&kind))
        .count()
}

/// Count `cron` rows in `pic triggers ls --app`.
fn app_cron_count(env: &common::TestEnv, app: &str) -> usize {
    app_trigger_count(env, app, "cron")
}

/// The `materialized` cell (index 6) of the first row of `kind` in
/// `pic triggers ls --app`. Columns: id kind script_id enabled dispatch
/// retry_max materialized created_at.
fn app_trigger_materialized(env: &common::TestEnv, app: &str, kind: &str) -> Option<String> {
    let out = common::pic_as(env)
        .args(["triggers", "ls", "--app", app])
        .output()
        .expect("triggers ls");
    String::from_utf8(out.stdout)
        .unwrap()
        .lines()
        .map(common::cells)
        .find(|c| c.get(1) == Some(&kind))
        .and_then(|c| c.get(6).map(|s| (*s).to_string()))
}

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

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

    // Group handler + a cron TEMPLATE binding it.
    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/nightly.rhai"),
        r#"log::info("nightly"); "ok""#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/nightly.rhai"))
        .args(["--group", &group, "--name", "nightly"])
        .assert()
        .success();
    let _gs = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "nightly"),
    );
    let gmanifest = format!(
        "[group]\nslug = \"{group}\"\nname = \"MatG\"\n\n\
         [[triggers.cron]]\nscript = \"nightly\"\nschedule = \"0 0 * * * *\"\n"
    );
    let gpath = dir.path().join("group.toml");
    fs::write(&gpath, &gmanifest).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();

    // An app created under the group materializes a per-app cron copy (the
    // app-create hook reconciles).
    let app = common::unique_slug("mat-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app, "--group", &group])
        .assert()
        .success();
    assert_eq!(
        app_cron_count(&env, &app),
        1,
        "a descendant app must have a materialized cron trigger"
    );
    // D1: the materialized copy reads `materialized = true` (inherited,
    // read-only) — distinct from a hand-authored trigger.
    assert_eq!(
        app_trigger_materialized(&env, &app, "cron").as_deref(),
        Some("true"),
        "a materialized cron copy must show materialized = true"
    );

    // Re-apply of the group is a NoOp for materialization (no duplicate copy).
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();
    assert_eq!(
        app_cron_count(&env, &app),
        1,
        "re-apply must not duplicate the materialized copy"
    );
}

/// §4.5 M5.5 — a group EMAIL template materializes for a descendant app. The
/// template resolves its `inbound_secret_ref` against the GROUP's own secret
/// store once at apply (shared-group-secret model); creating an app under the
/// group materializes a per-app email trigger, visible in `pic triggers ls
/// --app`. Re-applying the group is a NoOp (no duplicate copy).
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn group_email_template_materializes_for_descendant_apps() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let group = common::unique_slug("mat-em-grp");

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

    // A group secret the email template references, resolved at apply.
    common::pic_as(&env)
        .args(["secrets", "set", "--group", &group, "mail-sig"])
        .write_stdin("s3cret-hmac")
        .assert()
        .success();

    // Group handler + an email TEMPLATE binding it.
    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/inbound.rhai"),
        r#"log::info("inbound"); "ok""#,
    )
    .unwrap();
    common::pic_as(&env)
        .args(["scripts", "deploy"])
        .arg(dir.path().join("scripts/inbound.rhai"))
        .args(["--group", &group, "--name", "inbound"])
        .assert()
        .success();
    let _gs = ScriptGuard::new(
        &env.url,
        &env.token,
        &group_script_id(&env, &group, "inbound"),
    );
    let gmanifest = format!(
        "[group]\nslug = \"{group}\"\nname = \"MatEmG\"\n\n\
         [[triggers.email]]\nscript = \"inbound\"\ninbound_secret_ref = \"mail-sig\"\n"
    );
    let gpath = dir.path().join("group.toml");
    fs::write(&gpath, &gmanifest).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();

    // An app created under the group materializes a per-app email copy.
    let app = common::unique_slug("mat-em-app");
    let _a = AppGuard::new(&env.url, &env.token, &app);
    common::pic_as(&env)
        .args(["apps", "create", &app, "--group", &group])
        .assert()
        .success();
    assert_eq!(
        app_trigger_count(&env, &app, "email"),
        1,
        "a descendant app must have a materialized email trigger"
    );

    // Re-apply of the group is a NoOp for materialization (no duplicate copy).
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&gpath)
        .assert()
        .success();
    assert_eq!(
        app_trigger_count(&env, &app, "email"),
        1,
        "re-apply must not duplicate the materialized email copy"
    );
}
