//! Reqwest-backed HTTP client + minimal wire DTOs.
//!
//! The CLI deliberately re-declares small request/response structs here
//! rather than depending on `manager-core` (and pulling its Postgres
//! transitive surface). Fields kept to what the CLI actually sends or
//! reads.

use std::collections::BTreeMap;

use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
use picloud_shared::{
    AdminUserId, ApiKeyId, App, AppDomain, AppId, AppRole, AppUser, DispatchMode, ExecutionLog,
    Group, HostKind, InstanceRole, PathKind, Route, Scope, Script, ScriptId, ScriptKind,
    ScriptSandbox,
};
use reqwest::{header, Method, RequestBuilder, StatusCode};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::config::Credentials;

/// Characters that must be escaped inside a single URL **path segment** so
/// a free-form value (an app slug, a topic name) can't break out of its
/// segment — `/` would start a new segment, `?`/`#` would start the query
/// or fragment. Encodes controls, space, and the structural delimiters.
const PATH_SEGMENT: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'/')
    .add(b'?')
    .add(b'#')
    .add(b'%')
    .add(b'&')
    .add(b'+');

/// Percent-encode a value for safe interpolation into one path segment.
fn seg(s: &str) -> String {
    utf8_percent_encode(s, PATH_SEGMENT).to_string()
}

/// Build a `plan` request body: the bundle fields at the JSON top level plus an
/// optional `project` key (§7). The plan endpoints `#[serde(flatten)]` the
/// bundle, so a bare bundle (no `[project]`) is the pre-§7 wire shape — this
/// keeps `pic plan` compatible across a CLI/server version skew in either
/// direction (an old server ignores the extra `project`; a new server accepts
/// the bare bundle).
fn plan_body(
    bundle: &serde_json::Value,
    project: Option<&crate::manifest::ManifestProject>,
) -> Result<serde_json::Value> {
    let mut body = bundle.clone();
    if let Some(p) = project {
        if let Some(obj) = body.as_object_mut() {
            obj.insert("project".to_string(), serde_json::to_value(p)?);
        }
    }
    Ok(body)
}

pub struct Client {
    http: reqwest::Client,
    url: String,
    token: String,
}

impl Client {
    pub fn from_creds(creds: &Credentials) -> Result<Self> {
        Self::new(&creds.url, &creds.token)
    }

    pub fn new(url: &str, token: &str) -> Result<Self> {
        let http = reqwest::Client::builder()
            .user_agent(concat!("pic/", env!("CARGO_PKG_VERSION")))
            .build()
            .context("building HTTP client")?;
        Ok(Self {
            http,
            url: url.trim_end_matches('/').to_string(),
            token: token.to_string(),
        })
    }

    #[allow(dead_code)] // used by the trailing-slash unit test below.
    pub fn url(&self) -> &str {
        &self.url
    }

    fn request(&self, method: Method, path: &str) -> RequestBuilder {
        self.http
            .request(method, format!("{}{path}", self.url))
            .header(header::AUTHORIZATION, format!("Bearer {}", self.token))
    }

    /// `GET /api/v1/admin/auth/me`
    pub async fn auth_me(&self) -> Result<AuthMeDto> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/auth/me")
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps`
    pub async fn apps_list(&self) -> Result<Vec<App>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/apps")
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id_or_slug}` — slug or UUID accepted.
    pub async fn apps_get(&self, ident: &str) -> Result<AppLookupDto> {
        let ident = seg(ident);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{ident}"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps`
    pub async fn apps_create(&self, body: &CreateAppBody<'_>) -> Result<App> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/apps")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/scripts?app={ident}`
    pub async fn scripts_list_by_app(&self, ident: &str) -> Result<Vec<Script>> {
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/scripts?app={}", urlencoded(ident)),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/scripts` — every script the caller can see
    /// (server filters by membership for `Member`). Lets `pic scripts ls`
    /// (no `--app`) collapse what used to be an N+1 per-app walk into a
    /// single request that can't be partially-broken by a concurrent app
    /// delete.
    pub async fn scripts_list_all(&self) -> Result<Vec<Script>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/scripts")
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/apps/{id_or_slug}` with optional `?force=true`.
    /// Server requires `AppAdmin` capability; without `force`, returns
    /// 409 if the app still has scripts.
    pub async fn apps_delete(&self, ident: &str, force: bool) -> Result<()> {
        let ident = seg(ident);
        let path = if force {
            format!("/api/v1/admin/apps/{ident}?force=true")
        } else {
            format!("/api/v1/admin/apps/{ident}")
        };
        let resp = self.request(Method::DELETE, &path).send().await?;
        decode_status(resp).await
    }

    // --- Groups (Phase 2) -------------------------------------------------

    /// `GET /api/v1/admin/groups` — the full flat list (assemble the tree
    /// client-side from `parent_id`). Ignores the §7 `owner` field the server
    /// also returns (see [`Self::groups_list_with_owner`]).
    pub async fn groups_list(&self) -> Result<Vec<Group>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/groups")
            .send()
            .await?;
        decode(resp).await
    }

    /// Same endpoint as [`Self::groups_list`], but captures the §7 owning
    /// project's slug alongside each group — backs `pic groups ls`' owner
    /// column.
    pub async fn groups_list_with_owner(&self) -> Result<Vec<GroupListItem>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/groups")
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/projects` — every §7 project + its owned-group count.
    /// Backs `pic projects ls`.
    pub async fn projects_list(&self) -> Result<Vec<ProjectDto>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/projects")
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{id_or_slug}` — group + path + children.
    pub async fn groups_get(&self, ident: &str) -> Result<GroupDetailDto> {
        let ident = seg(ident);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/groups/{ident}"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/groups`
    pub async fn groups_create(&self, body: &CreateGroupBody<'_>) -> Result<Group> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/groups")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `PATCH /api/v1/admin/groups/{id_or_slug}` — name/description only
    /// (the slug is frozen).
    pub async fn groups_rename(
        &self,
        ident: &str,
        name: Option<&str>,
        description: Option<&str>,
    ) -> Result<Group> {
        let ident = seg(ident);
        let body = serde_json::json!({ "name": name, "description": description });
        let resp = self
            .request(Method::PATCH, &format!("/api/v1/admin/groups/{ident}"))
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/groups/{id_or_slug}/reparent` — `parent` is a
    /// slug/id, or `None` to move to root.
    pub async fn groups_reparent(&self, ident: &str, parent: Option<&str>) -> Result<Group> {
        let ident = seg(ident);
        let body = serde_json::json!({ "parent": parent });
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/groups/{ident}/reparent"),
            )
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/groups/{id_or_slug}` — 409 if non-empty.
    pub async fn groups_delete(&self, ident: &str) -> Result<()> {
        let ident = seg(ident);
        let resp = self
            .request(Method::DELETE, &format!("/api/v1/admin/groups/{ident}"))
            .send()
            .await?;
        decode_status(resp).await
    }

    pub async fn group_members_list(&self, group: &str) -> Result<Vec<AppMemberDto>> {
        let group = seg(group);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{group}/members"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    pub async fn group_members_grant(
        &self,
        group: &str,
        user_id: &str,
        role: AppRole,
    ) -> Result<AppMemberDto> {
        let group = seg(group);
        let body = serde_json::json!({ "user_id": user_id, "role": role });
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/groups/{group}/members"),
            )
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    pub async fn group_members_set_role(
        &self,
        group: &str,
        user_id: &str,
        role: AppRole,
    ) -> Result<AppMemberDto> {
        let (group, user_id) = (seg(group), seg(user_id));
        let body = serde_json::json!({ "role": role });
        let resp = self
            .request(
                Method::PATCH,
                &format!("/api/v1/admin/groups/{group}/members/{user_id}"),
            )
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    pub async fn group_members_remove(&self, group: &str, user_id: &str) -> Result<()> {
        let (group, user_id) = (seg(group), seg(user_id));
        let resp = self
            .request(
                Method::DELETE,
                &format!("/api/v1/admin/groups/{group}/members/{user_id}"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `DELETE /api/v1/admin/scripts/{id}` — requires `AppAdmin` on the
    /// owning app (stricter than the edit endpoints, by design).
    pub async fn scripts_delete(&self, id: &str) -> Result<()> {
        let id = seg(id);
        let resp = self
            .request(Method::DELETE, &format!("/api/v1/admin/scripts/{id}"))
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `POST /api/v1/admin/scripts`
    pub async fn scripts_create(&self, body: &CreateScriptBody<'_>) -> Result<Script> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/scripts")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{id_or_slug}/scripts` — a group's own
    /// scripts (Phase 4). Not inherited; just the group's rows.
    pub async fn group_scripts_list(&self, group_ident: &str) -> Result<Vec<Script>> {
        let g = seg(group_ident);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/groups/{g}/scripts"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/groups/{id_or_slug}/scripts` — create a
    /// group-owned script (Phase 4).
    pub async fn group_scripts_create(
        &self,
        group_ident: &str,
        body: &CreateGroupScriptBody<'_>,
    ) -> Result<Script> {
        let g = seg(group_ident);
        let resp = self
            .request(Method::POST, &format!("/api/v1/admin/groups/{g}/scripts"))
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `PUT /api/v1/admin/scripts/{id}` — matches the dashboard, which
    /// uses PUT despite the field-level update semantics. `cfg` carries
    /// optional per-script runtime overrides (G3); unset fields are
    /// omitted so they keep their stored value.
    pub async fn scripts_update_source(
        &self,
        id: &str,
        source: &str,
        cfg: &ScriptConfig,
    ) -> Result<Script> {
        let id = seg(id);
        let body = UpdateScriptBody {
            source,
            timeout_seconds: cfg.timeout_seconds,
            memory_limit_mb: cfg.memory_limit_mb,
            kind: cfg.kind,
            sandbox: cfg.sandbox,
        };
        let resp = self
            .request(Method::PUT, &format!("/api/v1/admin/scripts/{id}"))
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/execute/{id}` — returns the raw HTTP status, headers,
    /// and JSON body (the orchestrator marshals the script's output as
    /// the HTTP response itself, not a wrapper object).
    pub async fn execute(
        &self,
        id: &str,
        body: Value,
        headers: &[(String, String)],
    ) -> Result<ExecuteResponse> {
        let id = seg(id);
        let mut req = self
            .request(Method::POST, &format!("/api/v1/execute/{id}"))
            .json(&body);
        for (k, v) in headers {
            req = req.header(k, v);
        }
        let resp = req.send().await?;
        let status = resp.status().as_u16();
        let mut headers_out: BTreeMap<String, String> = BTreeMap::new();
        for (k, v) in resp.headers() {
            if let Ok(val) = v.to_str() {
                headers_out.insert(k.as_str().to_string(), val.to_string());
            }
        }
        let bytes = resp.bytes().await.context("reading execute response")?;
        let body_json: Value = if bytes.is_empty() {
            Value::Null
        } else {
            serde_json::from_slice(&bytes)
                .unwrap_or(Value::String(String::from_utf8_lossy(&bytes).into_owned()))
        };
        Ok(ExecuteResponse {
            status_code: status,
            headers: headers_out,
            body: body_json,
        })
    }

    /// `GET /api/v1/admin/scripts/{id}/logs?limit=N`
    pub async fn logs_list(
        &self,
        script_id: &str,
        limit: u32,
        source: Option<&str>,
    ) -> Result<Vec<ExecutionLog>> {
        let script_id = seg(script_id);
        let mut path = format!("/api/v1/admin/scripts/{script_id}/logs?limit={limit}");
        if let Some(src) = source {
            path.push_str("&source=");
            path.push_str(&seg(src));
        }
        let resp = self.request(Method::GET, &path).send().await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/auth/logout` — best-effort: server returns
    /// 204 whether or not the token matched a live session, so we just
    /// fire and discard the body. Caller still wipes the local creds.
    pub async fn auth_logout(&self) -> Result<()> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/auth/logout")
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `GET /api/v1/admin/api-keys` — caller's keys only (server filters
    /// by user_id, no cross-user enumeration).
    pub async fn apikeys_list(&self) -> Result<Vec<ApiKeyDto>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/api-keys")
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/api-keys` — `raw_token` is in the response
    /// **once** and never appears in `GET /api-keys` afterward.
    pub async fn apikeys_mint(&self, body: &MintApiKeyBody<'_>) -> Result<MintApiKeyResponseDto> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/api-keys")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/api-keys/{id}` — 404 covers both "doesn't
    /// exist" and "not yours" (server flattens to avoid enumeration).
    pub async fn apikeys_delete(&self, id: &str) -> Result<()> {
        let id = seg(id);
        let resp = self
            .request(Method::DELETE, &format!("/api/v1/admin/api-keys/{id}"))
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `GET /api/v1/admin/scripts/{id}/routes`
    pub async fn routes_list_for_script(&self, script_id: &str) -> Result<Vec<Route>> {
        let script_id = seg(script_id);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/scripts/{script_id}/routes"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/scripts/{id}/routes`
    pub async fn routes_create(
        &self,
        script_id: &str,
        body: &CreateRouteBody<'_>,
    ) -> Result<Route> {
        let script_id = seg(script_id);
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/scripts/{script_id}/routes"),
            )
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/routes/{route_id}`
    pub async fn routes_delete(&self, route_id: &str) -> Result<()> {
        let route_id = seg(route_id);
        let resp = self
            .request(Method::DELETE, &format!("/api/v1/admin/routes/{route_id}"))
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `POST /api/v1/admin/routes:check` — dry-run conflict check for a
    /// hypothetical route, scoped to one app.
    pub async fn routes_check(&self, body: &CheckRouteBody) -> Result<CheckRouteResponseDto> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/routes:check")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/routes:match` — what route would the given
    /// URL+method match, if any, for the given app.
    pub async fn routes_match(&self, body: &MatchRouteBody<'_>) -> Result<MatchRouteResponseDto> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/routes:match")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/admins`
    pub async fn admins_list(&self) -> Result<Vec<AdminDto>> {
        let resp = self
            .request(Method::GET, "/api/v1/admin/admins")
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/admins/{id}`
    pub async fn admins_get(&self, id: &str) -> Result<AdminDto> {
        let id = seg(id);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/admins/{id}"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/admins`
    pub async fn admins_create(&self, body: &CreateAdminBody<'_>) -> Result<AdminDto> {
        let resp = self
            .request(Method::POST, "/api/v1/admin/admins")
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `PATCH /api/v1/admin/admins/{id}`
    pub async fn admins_patch(&self, id: &str, body: &PatchAdminBody<'_>) -> Result<AdminDto> {
        let id = seg(id);
        let resp = self
            .request(Method::PATCH, &format!("/api/v1/admin/admins/{id}"))
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/admins/{id}`
    pub async fn admins_delete(&self, id: &str) -> Result<()> {
        let id = seg(id);
        let resp = self
            .request(Method::DELETE, &format!("/api/v1/admin/admins/{id}"))
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/triggers`
    pub async fn triggers_list(&self, app: &str) -> Result<TriggerListDto> {
        let app = seg(app);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{app}/triggers"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/workflows`
    pub async fn workflows_list(&self, app: &str) -> Result<Vec<WorkflowDto>> {
        let app = seg(app);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{app}/workflows"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id}/workflows/{name}/runs` — start a run.
    pub async fn workflow_run_start(
        &self,
        app: &str,
        name: &str,
        input: serde_json::Value,
    ) -> Result<WorkflowRunDto> {
        let (app, name) = (seg(app), seg(name));
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/apps/{app}/workflows/{name}/runs"),
            )
            .json(&serde_json::json!({ "input": input }))
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/workflows/{name}/runs` — recent runs.
    pub async fn workflow_runs_list(&self, app: &str, name: &str) -> Result<Vec<WorkflowRunDto>> {
        let (app, name) = (seg(app), seg(name));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/workflows/{name}/runs"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/workflow-runs/{run_id}` — one run + steps.
    pub async fn workflow_run_status(
        &self,
        app: &str,
        run_id: &str,
    ) -> Result<WorkflowRunDetailDto> {
        let (app, run_id) = (seg(app), seg(run_id));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/workflow-runs/{run_id}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/apps/{id}/triggers/{trigger_id}`
    pub async fn triggers_delete(&self, app: &str, trigger_id: &str) -> Result<()> {
        let (app, trigger_id) = (seg(app), seg(trigger_id));
        let resp = self
            .request(
                Method::DELETE,
                &format!("/api/v1/admin/apps/{app}/triggers/{trigger_id}"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `POST /api/v1/admin/apps/{id}/triggers/{kind}` — the body shape
    /// depends on `kind`; the CLI passes a pre-built JSON value so
    /// each create subcommand can construct its own per-kind body.
    pub async fn triggers_create(
        &self,
        app: &str,
        kind: &str,
        body: &serde_json::Value,
    ) -> Result<TriggerDto> {
        let (app, kind) = (seg(app), seg(kind));
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/apps/{app}/triggers/{kind}"),
            )
            .json(body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/dead_letters/count`
    pub async fn dead_letters_count(&self, app: &str) -> Result<DeadLetterCountDto> {
        let app = seg(app);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/dead_letters/count"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/dead_letters?unresolved={bool}&limit={n}`
    pub async fn dead_letters_list(
        &self,
        app: &str,
        unresolved: bool,
        limit: u32,
    ) -> Result<DeadLetterListDto> {
        let app = seg(app);
        let path =
            format!("/api/v1/admin/apps/{app}/dead_letters?unresolved={unresolved}&limit={limit}");
        let resp = self.request(Method::GET, &path).send().await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/dead_letters/{dl_id}`
    pub async fn dead_letters_get(&self, app: &str, dl_id: &str) -> Result<DeadLetterDto> {
        let (app, dl_id) = (seg(app), seg(dl_id));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/dead_letters/{dl_id}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id}/dead_letters/{dl_id}/replay`
    pub async fn dead_letters_replay(&self, app: &str, dl_id: &str) -> Result<()> {
        let (app, dl_id) = (seg(app), seg(dl_id));
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/apps/{app}/dead_letters/{dl_id}/replay"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `POST /api/v1/admin/apps/{id}/dead_letters/{dl_id}/resolve`
    pub async fn dead_letters_resolve(&self, app: &str, dl_id: &str, reason: &str) -> Result<()> {
        let (app, dl_id) = (seg(app), seg(dl_id));
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/apps/{app}/dead_letters/{dl_id}/resolve"),
            )
            .json(&serde_json::json!({ "reason": reason }))
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `GET /api/v1/admin/{apps,groups}/{id}/secrets` — secret names +
    /// last-modified for the owner. Values never travel on this path. `env`
    /// is only meaningful for group owners (app secrets are env-agnostic).
    pub async fn secrets_list(
        &self,
        owner: VarOwnerArg<'_>,
        env: Option<&str>,
    ) -> Result<SecretListDto> {
        let mut path = format!("{}/secrets", owner.base_path());
        if let Some(env) = env {
            path.push_str(&format!("?env={}", seg(env)));
        }
        let resp = self.request(Method::GET, &path).send().await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/{apps,groups}/{id}/secrets`. `env` rides in the
    /// body and is only honored by group owners.
    pub async fn secrets_set(
        &self,
        owner: VarOwnerArg<'_>,
        name: &str,
        value: serde_json::Value,
        env: Option<&str>,
    ) -> Result<()> {
        // `name` travels in the JSON body, not the path.
        let mut body = serde_json::json!({ "name": name, "value": value });
        if let Some(env) = env {
            body["env"] = serde_json::Value::String(env.to_string());
        }
        let resp = self
            .request(Method::POST, &format!("{}/secrets", owner.base_path()))
            .json(&body)
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `DELETE /api/v1/admin/{apps,groups}/{id}/secrets/{name}`
    pub async fn secrets_delete(
        &self,
        owner: VarOwnerArg<'_>,
        name: &str,
        env: Option<&str>,
    ) -> Result<()> {
        let mut path = format!("{}/secrets/{}", owner.base_path(), seg(name));
        if let Some(env) = env {
            path.push_str(&format!("?env={}", seg(env)));
        }
        let resp = self.request(Method::DELETE, &path).send().await?;
        decode_status(resp).await
    }

    /// `GET /api/v1/admin/groups/{id}/secrets/{name}/value` — the ONLY path
    /// that returns a decrypted secret value. Gated server-side at the owning
    /// group; there is no app-secret equivalent by design.
    pub async fn group_secret_read_value(
        &self,
        group: &str,
        name: &str,
        env: Option<&str>,
    ) -> Result<SecretValueDto> {
        let (group, name) = (seg(group), seg(name));
        let mut path = format!("/api/v1/admin/groups/{group}/secrets/{name}/value");
        if let Some(env) = env {
            path.push_str(&format!("?env={}", seg(env)));
        }
        let resp = self.request(Method::GET, &path).send().await?;
        decode(resp).await
    }

    // ---------- vars (Phase 3 config) ----------

    /// `GET /api/v1/admin/{apps,groups}/{id}/vars` — the owner's OWN vars
    /// (not the resolved/inherited view).
    pub async fn vars_list(&self, owner: VarOwnerArg<'_>) -> Result<VarListDto> {
        let resp = self
            .request(Method::GET, &format!("{}/vars", owner.base_path()))
            .send()
            .await?;
        decode(resp).await
    }

    /// `PUT /api/v1/admin/{apps,groups}/{id}/vars`
    pub async fn vars_set(
        &self,
        owner: VarOwnerArg<'_>,
        key: &str,
        value: serde_json::Value,
        env: Option<&str>,
        tombstone: bool,
    ) -> Result<()> {
        let mut body = serde_json::json!({ "key": key, "value": value, "tombstone": tombstone });
        if let Some(env) = env {
            body["env"] = serde_json::Value::String(env.to_string());
        }
        let resp = self
            .request(Method::PUT, &format!("{}/vars", owner.base_path()))
            .json(&body)
            .send()
            .await?;
        decode_status(resp).await
    }

    /// `DELETE /api/v1/admin/{apps,groups}/{id}/vars/{key}`
    pub async fn vars_delete(
        &self,
        owner: VarOwnerArg<'_>,
        key: &str,
        env: Option<&str>,
    ) -> Result<()> {
        let mut path = format!("{}/vars/{}", owner.base_path(), seg(key));
        if let Some(env) = env {
            path.push_str(&format!("?env={}", seg(env)));
        }
        let resp = self.request(Method::DELETE, &path).send().await?;
        decode_status(resp).await
    }

    /// `GET /api/v1/admin/apps/{id}/config/effective` — the app's resolved
    /// (group-inherited) vars plus masked secret statuses, each annotated with
    /// the owner that won and the layers it merged from (§4.6).
    pub async fn config_effective(&self, app: &str) -> Result<EffectiveConfigDto> {
        let app = seg(app);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/config/effective"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    // ---------- domains ----------

    /// `GET /api/v1/admin/apps/{id_or_slug}/domains`
    pub async fn domains_list(&self, app: &str) -> Result<Vec<AppDomain>> {
        let app = seg(app);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{app}/domains"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id_or_slug}/domains`
    pub async fn domains_create(&self, app: &str, pattern: &str) -> Result<AppDomain> {
        let app = seg(app);
        let resp = self
            .request(Method::POST, &format!("/api/v1/admin/apps/{app}/domains"))
            .json(&serde_json::json!({ "pattern": pattern }))
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/apps/{id_or_slug}/domains/{domain_id}`
    pub async fn domains_delete(&self, app: &str, domain_id: &str) -> Result<()> {
        let (app, domain_id) = (seg(app), seg(domain_id));
        let resp = self
            .request(
                Method::DELETE,
                &format!("/api/v1/admin/apps/{app}/domains/{domain_id}"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    // ---------- topics ----------

    /// `GET /api/v1/admin/apps/{id_or_slug}/topics`
    pub async fn topics_list(&self, app: &str) -> Result<Vec<TopicDto>> {
        let app = seg(app);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{app}/topics"))
            .send()
            .await?;
        let body: TopicListDto = decode(resp).await?;
        Ok(body.topics)
    }

    /// `POST /api/v1/admin/apps/{id_or_slug}/topics`
    pub async fn topics_create(
        &self,
        app: &str,
        name: &str,
        external_subscribable: bool,
        auth_mode: &str,
    ) -> Result<TopicDto> {
        let app = seg(app);
        let resp = self
            .request(Method::POST, &format!("/api/v1/admin/apps/{app}/topics"))
            .json(&serde_json::json!({
                "name": name,
                "external_subscribable": external_subscribable,
                "auth_mode": auth_mode,
            }))
            .send()
            .await?;
        decode(resp).await
    }

    /// `PATCH /api/v1/admin/apps/{id_or_slug}/topics/{name}` — only the
    /// fields the caller set are sent; the server leaves the rest alone.
    pub async fn topics_update(
        &self,
        app: &str,
        name: &str,
        external_subscribable: Option<bool>,
        auth_mode: Option<&str>,
    ) -> Result<TopicDto> {
        let mut body = serde_json::Map::new();
        if let Some(e) = external_subscribable {
            body.insert("external_subscribable".into(), Value::Bool(e));
        }
        if let Some(m) = auth_mode {
            body.insert("auth_mode".into(), Value::String(m.to_string()));
        }
        let (app, name) = (seg(app), seg(name));
        let resp = self
            .request(
                Method::PATCH,
                &format!("/api/v1/admin/apps/{app}/topics/{name}"),
            )
            .json(&Value::Object(body))
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/apps/{id_or_slug}/topics/{name}`
    pub async fn topics_delete(&self, app: &str, name: &str) -> Result<()> {
        let (app, name) = (seg(app), seg(name));
        let resp = self
            .request(
                Method::DELETE,
                &format!("/api/v1/admin/apps/{app}/topics/{name}"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    // ---------- app end-users ----------

    /// `GET /api/v1/admin/apps/{id_or_slug}/users?limit={n}`
    pub async fn app_users_list(&self, app: &str, limit: u32) -> Result<Vec<AppUser>> {
        let app = seg(app);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/users?limit={limit}"),
            )
            .send()
            .await?;
        let body: ListUsersResponseDto = decode(resp).await?;
        Ok(body.users)
    }

    /// `GET /api/v1/admin/apps/{id_or_slug}/users/{user_id}`
    pub async fn app_user_get(&self, app: &str, user_id: &str) -> Result<AppUser> {
        let (app, user_id) = (seg(app), seg(user_id));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/users/{user_id}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id_or_slug}/users/{user_id}/reset-password`
    pub async fn app_user_reset_password(
        &self,
        app: &str,
        user_id: &str,
    ) -> Result<ResetPasswordResponseDto> {
        let (app, user_id) = (seg(app), seg(user_id));
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/apps/{app}/users/{user_id}/reset-password"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id_or_slug}/users/{user_id}/revoke-sessions`
    pub async fn app_user_revoke_sessions(
        &self,
        app: &str,
        user_id: &str,
    ) -> Result<RevokeSessionsResponseDto> {
        let (app, user_id) = (seg(app), seg(user_id));
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/apps/{app}/users/{user_id}/revoke-sessions"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    // --- App membership (G2) ----------------------------------------------

    /// `GET /api/v1/admin/apps/{id_or_slug}/members`
    pub async fn members_list(&self, app: &str) -> Result<Vec<AppMemberDto>> {
        let app = seg(app);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{app}/members"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id_or_slug}/members`
    pub async fn members_grant(
        &self,
        app: &str,
        user_id: &str,
        role: AppRole,
    ) -> Result<AppMemberDto> {
        let app = seg(app);
        let body = serde_json::json!({ "user_id": user_id, "role": role });
        let resp = self
            .request(Method::POST, &format!("/api/v1/admin/apps/{app}/members"))
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `PATCH /api/v1/admin/apps/{id_or_slug}/members/{user_id}`
    pub async fn members_set_role(
        &self,
        app: &str,
        user_id: &str,
        role: AppRole,
    ) -> Result<AppMemberDto> {
        let (app, user_id) = (seg(app), seg(user_id));
        let body = serde_json::json!({ "role": role });
        let resp = self
            .request(
                Method::PATCH,
                &format!("/api/v1/admin/apps/{app}/members/{user_id}"),
            )
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `DELETE /api/v1/admin/apps/{id_or_slug}/members/{user_id}`
    pub async fn members_remove(&self, app: &str, user_id: &str) -> Result<()> {
        let (app, user_id) = (seg(app), seg(user_id));
        let resp = self
            .request(
                Method::DELETE,
                &format!("/api/v1/admin/apps/{app}/members/{user_id}"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    // --- Files (G2, read-only admin surface) ------------------------------

    /// `GET /api/v1/admin/apps/{id_or_slug}/files?collection=&limit=`
    pub async fn files_list(
        &self,
        app: &str,
        collection: &str,
        limit: u32,
    ) -> Result<ListFilesResponse> {
        let app = seg(app);
        let collection = seg(collection);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/files?collection={collection}&limit={limit}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id_or_slug}/files/{collection}/{file_id}` —
    /// streams the raw bytes (download). Returns the body verbatim.
    pub async fn files_get_bytes(
        &self,
        app: &str,
        collection: &str,
        file_id: &str,
    ) -> Result<Vec<u8>> {
        let (app, collection, file_id) = (seg(app), seg(collection), seg(file_id));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/files/{collection}/{file_id}"),
            )
            .send()
            .await?;
        if resp.status().is_success() {
            Ok(resp.bytes().await.context("reading file bytes")?.to_vec())
        } else {
            Err(server_error(resp).await)
        }
    }

    /// §11.6 M4: a group's shared-files collection (read-only admin surface).
    /// `GET /api/v1/admin/groups/{id_or_slug}/files?collection=&limit=`
    pub async fn group_files_list(
        &self,
        group: &str,
        collection: &str,
        limit: u32,
    ) -> Result<ListFilesResponse> {
        let (group, collection) = (seg(group), seg(collection));
        let resp = self
            .request(
                Method::GET,
                &format!(
                    "/api/v1/admin/groups/{group}/files?collection={collection}&limit={limit}"
                ),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{id_or_slug}/files/{collection}/{file_id}` —
    /// streams a shared file's raw bytes (download).
    pub async fn group_files_get_bytes(
        &self,
        group: &str,
        collection: &str,
        file_id: &str,
    ) -> Result<Vec<u8>> {
        let (group, collection, file_id) = (seg(group), seg(collection), seg(file_id));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{group}/files/{collection}/{file_id}"),
            )
            .send()
            .await?;
        if resp.status().is_success() {
            Ok(resp.bytes().await.context("reading file bytes")?.to_vec())
        } else {
            Err(server_error(resp).await)
        }
    }

    /// `DELETE /api/v1/admin/apps/{id_or_slug}/files/{collection}/{file_id}`
    pub async fn files_delete(&self, app: &str, collection: &str, file_id: &str) -> Result<()> {
        let (app, collection, file_id) = (seg(app), seg(collection), seg(file_id));
        let resp = self
            .request(
                Method::DELETE,
                &format!("/api/v1/admin/apps/{app}/files/{collection}/{file_id}"),
            )
            .send()
            .await?;
        decode_status(resp).await
    }

    // --- KV (G2, read-only admin surface) ---------------------------------

    /// `GET /api/v1/admin/apps/{id_or_slug}/kv?collection=&limit=`
    pub async fn kv_list(&self, app: &str, collection: &str, limit: u32) -> Result<KvListPageDto> {
        let app = seg(app);
        let collection = seg(collection);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/kv?collection={collection}&limit={limit}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id_or_slug}/kv/{collection}/{key}`
    pub async fn kv_get(&self, app: &str, collection: &str, key: &str) -> Result<Value> {
        let (app, collection, key) = (seg(app), seg(collection), seg(key));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/kv/{collection}/{key}"),
            )
            .send()
            .await?;
        let wrapped: KvGetResponse = decode(resp).await?;
        Ok(wrapped.value)
    }

    /// §11.6 M4: a group's shared-KV collection.
    /// `GET /api/v1/admin/groups/{id_or_slug}/kv?collection=…`
    pub async fn group_kv_list(
        &self,
        group: &str,
        collection: &str,
        limit: u32,
    ) -> Result<KvListPageDto> {
        let (group, collection) = (seg(group), seg(collection));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{group}/kv?collection={collection}&limit={limit}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{id_or_slug}/kv/{collection}/{key}`
    pub async fn group_kv_get(&self, group: &str, collection: &str, key: &str) -> Result<Value> {
        let (group, collection, key) = (seg(group), seg(collection), seg(key));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{group}/kv/{collection}/{key}"),
            )
            .send()
            .await?;
        let wrapped: KvGetResponse = decode(resp).await?;
        Ok(wrapped.value)
    }

    /// §11.6: a group's shared-docs collection (operator read).
    /// `GET /api/v1/admin/groups/{id_or_slug}/docs?collection=…&limit=…`
    pub async fn group_docs_list(
        &self,
        group: &str,
        collection: &str,
        limit: u32,
    ) -> Result<GroupDocsListDto> {
        let (group, collection) = (seg(group), seg(collection));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{group}/docs?collection={collection}&limit={limit}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{id_or_slug}/docs/{collection}/{doc_id}`
    pub async fn group_docs_get(
        &self,
        group: &str,
        collection: &str,
        doc_id: &str,
    ) -> Result<Value> {
        let (group, collection, doc_id) = (seg(group), seg(collection), seg(doc_id));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{group}/docs/{collection}/{doc_id}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// §11.6 D3: a group's shared-queue dead-letters (operator read; list-only).
    /// `GET /api/v1/admin/groups/{id_or_slug}/dead-letters?unresolved=…&limit=…`
    pub async fn group_dead_letters_list(
        &self,
        group: &str,
        unresolved: bool,
        limit: u32,
    ) -> Result<Vec<GroupDeadLetterDto>> {
        let group = seg(group);
        let resp = self
            .request(
                Method::GET,
                &format!(
                    "/api/v1/admin/groups/{group}/dead-letters?unresolved={unresolved}&limit={limit}"
                ),
            )
            .send()
            .await?;
        decode(resp).await
    }

    // --- Queues (G2, read-only admin surface) -----------------------------

    /// `GET /api/v1/admin/apps/{id_or_slug}/queues`
    pub async fn queues_list(&self, app: &str) -> Result<Vec<QueueSummaryDto>> {
        let app = seg(app);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/apps/{app}/queues"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{id_or_slug}/queues/{queue_name}`
    pub async fn queue_get(&self, app: &str, queue_name: &str) -> Result<QueueDetailDto> {
        let (app, queue_name) = (seg(app), seg(queue_name));
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{app}/queues/{queue_name}"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/apps/{id_or_slug}/plan` — diff a desired-state
    /// bundle against the app's live state. Read-only.
    /// `POST /api/v1/admin/{apps|groups}/{id_or_slug}/plan` — diff a bundle
    /// against an app OR group node (Phase 5).
    pub async fn plan_node(
        &self,
        kind: NodeKind,
        slug: &str,
        bundle: &serde_json::Value,
        project: Option<&crate::manifest::ManifestProject>,
    ) -> Result<PlanDto> {
        let slug = seg(slug);
        let body = plan_body(bundle, project)?;
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/{}/{slug}/plan", kind.path()),
            )
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/{apps|groups}/{id_or_slug}/apply` — reconcile an
    /// app OR group node in one transaction (Phase 5).
    #[allow(clippy::too_many_arguments)]
    pub async fn apply_node(
        &self,
        kind: NodeKind,
        slug: &str,
        bundle: &serde_json::Value,
        prune: bool,
        project: Option<&crate::manifest::ManifestProject>,
        takeover: bool,
        expected_token: Option<&str>,
        env: Option<&str>,
        approved_envs: &[String],
    ) -> Result<ApplyReportDto> {
        let slug = seg(slug);
        let body = serde_json::json!({
            "bundle": bundle,
            "prune": prune,
            "expected_token": expected_token,
            "project": project,
            "takeover": takeover,
            "env": env,
            "approved_envs": approved_envs,
        });
        let resp = self
            .request(
                Method::POST,
                &format!("/api/v1/admin/{}/{slug}/apply", kind.path()),
            )
            .json(&body)
            .send()
            .await?;
        // The apply endpoint returns 409 for a stale bound plan (`StateMoved`)
        // OR a §7 ownership conflict. Both server messages are self-contained
        // and actionable, so surface the message verbatim.
        if resp.status() == reqwest::StatusCode::CONFLICT {
            let body = resp.text().await.unwrap_or_default();
            let msg = parse_error_body(&body).unwrap_or(body);
            return Err(anyhow!("{msg}"));
        }
        decode(resp).await
    }

    /// `POST /api/v1/admin/tree/plan` — diff a whole project tree (Phase 5).
    pub async fn plan_tree(
        &self,
        bundle: &serde_json::Value,
        project: Option<&crate::manifest::ManifestProject>,
    ) -> Result<TreePlanDto> {
        let body = plan_body(bundle, project)?;
        let resp = self
            .request(Method::POST, "/api/v1/admin/tree/plan")
            .json(&body)
            .send()
            .await?;
        decode(resp).await
    }

    /// `POST /api/v1/admin/tree/apply` — reconcile a whole project tree in one
    /// transaction (Phase 5).
    #[allow(clippy::too_many_arguments)]
    pub async fn apply_tree(
        &self,
        bundle: &serde_json::Value,
        prune: bool,
        project: Option<&crate::manifest::ManifestProject>,
        takeover: bool,
        expected_token: Option<&str>,
        structure_mode: &str,
        env: Option<&str>,
        approved_envs: &[String],
    ) -> Result<ApplyReportDto> {
        let body = serde_json::json!({
            "bundle": bundle,
            "prune": prune,
            "expected_token": expected_token,
            "project": project,
            "takeover": takeover,
            "structure_mode": structure_mode,
            "env": env,
            "approved_envs": approved_envs,
        });
        let resp = self
            .request(Method::POST, "/api/v1/admin/tree/apply")
            .json(&body)
            .send()
            .await?;
        // 409 = stale bound plan OR a §7 ownership conflict; 422 = a §6 M2
        // structural divergence (or an invalid bundle). Surface the server
        // message verbatim — it names the resolution flags.
        let status = resp.status();
        if status == reqwest::StatusCode::CONFLICT
            || status == reqwest::StatusCode::UNPROCESSABLE_ENTITY
        {
            let body = resp.text().await.unwrap_or_default();
            let msg = parse_error_body(&body).unwrap_or(body);
            return Err(anyhow!("{msg}"));
        }
        decode(resp).await
    }
}

/// `POST /api/v1/admin/auth/login` — sits outside the `Client` because
/// it runs before any token exists. Mirrors the dashboard's login.ts
/// wire shape (see `manager-core/src/auth_api.rs:49-60`).
pub async fn auth_login(url: &str, username: &str, password: &str) -> Result<LoginResponseDto> {
    let http = reqwest::Client::builder()
        .user_agent(concat!("pic/", env!("CARGO_PKG_VERSION")))
        .build()
        .context("building HTTP client")?;
    let body = LoginRequestBody { username, password };
    let resp = http
        .post(format!(
            "{}/api/v1/admin/auth/login",
            url.trim_end_matches('/')
        ))
        .json(&body)
        .send()
        .await?;
    decode(resp).await
}

/// Which kind of node a plan/apply targets (Phase 5) — selects the API path
/// prefix (`apps` vs `groups`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NodeKind {
    App,
    Group,
}

impl NodeKind {
    fn path(self) -> &'static str {
        match self {
            Self::App => "apps",
            Self::Group => "groups",
        }
    }
}

/// One row of the §5.5 extension-point report.
#[derive(Debug, Deserialize)]
pub struct ExtensionPointInfoDto {
    pub name: String,
    #[serde(default)]
    pub declared_here: bool,
    #[serde(default)]
    pub provider: Option<String>,
}

impl Client {
    /// `GET /api/v1/admin/{apps|groups}/{ident}/extension-points`.
    pub async fn extension_points_list(
        &self,
        kind: NodeKind,
        ident: &str,
    ) -> Result<Vec<ExtensionPointInfoDto>> {
        let ident = seg(ident);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/{}/{ident}/extension-points", kind.path()),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{ident}/collections` (§11.6). Group-only —
    /// shared collections are declared on groups.
    pub async fn collections_list(&self, group_ident: &str) -> Result<Vec<CollectionInfoDto>> {
        let ident = seg(group_ident);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{ident}/collections"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{ident}/triggers` (§11 tail). Group-only —
    /// trigger templates are declared on groups and fan out to descendant apps.
    pub async fn group_triggers_list(&self, group_ident: &str) -> Result<Vec<TriggerTemplateDto>> {
        let ident = seg(group_ident);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{ident}/triggers"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/groups/{ident}/routes` (§11 tail). Group-only — route
    /// templates are declared on groups and inherited by descendant apps.
    pub async fn group_routes_list(&self, group_ident: &str) -> Result<Vec<RouteTemplateDto>> {
        let ident = seg(group_ident);
        let resp = self
            .request(Method::GET, &format!("/api/v1/admin/groups/{ident}/routes"))
            .send()
            .await?;
        decode(resp).await
    }

    /// `GET /api/v1/admin/apps/{ident}/suppressions` (§11 tail). App-only — the
    /// inherited templates the app declines.
    pub async fn suppressions_list(&self, app_ident: &str) -> Result<Vec<SuppressionDto>> {
        let ident = seg(app_ident);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/apps/{ident}/suppressions"),
            )
            .send()
            .await?;
        decode(resp).await
    }

    /// §11 tail M1: a group's own suppressions (declined for its whole subtree).
    pub async fn group_suppressions_list(&self, group_ident: &str) -> Result<Vec<SuppressionDto>> {
        let ident = seg(group_ident);
        let resp = self
            .request(
                Method::GET,
                &format!("/api/v1/admin/groups/{ident}/suppressions"),
            )
            .send()
            .await?;
        decode(resp).await
    }
}

/// One row of the §11 tail suppression report.
#[derive(Debug, Deserialize)]
pub struct SuppressionDto {
    #[serde(default)]
    pub target_kind: String,
    #[serde(default)]
    pub reference: String,
}

/// One row of the §11 tail trigger-template report.
#[derive(Debug, Deserialize)]
pub struct TriggerTemplateDto {
    pub kind: String,
    #[serde(default)]
    pub target: String,
    #[serde(default)]
    pub script: String,
    pub enabled: bool,
    /// §11 tail: `true` for a sealed (non-suppressible) template.
    #[serde(default)]
    pub sealed: bool,
    /// §11.6: `true` for a shared-collection template.
    #[serde(default)]
    pub shared: bool,
}

/// One row of the §11 tail route-template report.
#[derive(Debug, Deserialize)]
pub struct RouteTemplateDto {
    #[serde(default)]
    pub method: String,
    #[serde(default)]
    pub host: String,
    #[serde(default)]
    pub path_kind: String,
    #[serde(default)]
    pub path: String,
    #[serde(default)]
    pub script: String,
    #[serde(default)]
    pub dispatch: String,
    pub enabled: bool,
    /// §11 tail: `true` for a sealed (non-suppressible) template.
    #[serde(default)]
    pub sealed: bool,
}

/// One row of the §11.6 shared-collection report.
#[derive(Debug, Deserialize)]
pub struct CollectionInfoDto {
    pub name: String,
    #[serde(default)]
    pub kind: String,
}

// ---------- DTOs (CLI-local, wire-shape-matched) ----------

/// Response of `POST .../plan`: per-resource diffs grouped by kind.
#[derive(Debug, Deserialize)]
pub struct PlanDto {
    #[serde(default)]
    pub scripts: Vec<ChangeDto>,
    #[serde(default)]
    pub routes: Vec<ChangeDto>,
    #[serde(default)]
    pub triggers: Vec<ChangeDto>,
    #[serde(default)]
    pub secrets: Vec<ChangeDto>,
    #[serde(default)]
    pub vars: Vec<ChangeDto>,
    #[serde(default)]
    pub extension_points: Vec<ChangeDto>,
    #[serde(default)]
    pub collections: Vec<ChangeDto>,
    #[serde(default)]
    pub suppressions: Vec<ChangeDto>,
    #[serde(default)]
    pub workflows: Vec<ChangeDto>,
    #[serde(default)]
    pub interceptors: Vec<ChangeDto>,
    /// Fingerprint of the live state this plan was computed against; carried
    /// in `.picloud/` and replayed to `apply` for the bound-plan check.
    #[serde(default)]
    pub state_token: String,
    /// §7 M3: the ownership outcome this apply would produce.
    #[serde(default)]
    pub ownership: Option<OwnershipPreviewDto>,
    /// §3 M3: envs the governing project marks confirm-required (need `--approve`).
    #[serde(default)]
    pub approvals_required: Vec<String>,
    /// Desired-state warnings `apply` would emit, previewed at plan (disabled
    /// binding, unreachable endpoint, dangling suppress).
    #[serde(default)]
    pub warnings: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct ChangeDto {
    pub op: String,
    pub key: String,
    #[serde(default)]
    pub detail: Option<String>,
}

/// §7 M3 plan preview: `action` ∈ claim/owned/conflict/unclaimed; `owner` is
/// the current owner's slug (for owned/conflict); `blast_radius` (M3.2) lists
/// other projects' apps a group change fans out to.
#[derive(Debug, Deserialize)]
pub struct OwnershipPreviewDto {
    pub action: String,
    #[serde(default)]
    pub owner: Option<String>,
    #[serde(default)]
    pub blast_radius: Vec<ProjectImpactDto>,
}

#[derive(Debug, Deserialize)]
pub struct ProjectImpactDto {
    pub project: String,
    pub apps: u32,
}

/// Response of `POST .../tree/plan` (Phase 5): a per-node diff + one combined
/// bound-plan token for the whole subtree.
#[derive(Debug, Deserialize)]
pub struct TreePlanDto {
    #[serde(default)]
    pub nodes: Vec<NodePlanDto>,
    #[serde(default)]
    pub state_token: String,
    /// §3 M3: envs the project marks confirm-required (need `--approve <env>`).
    #[serde(default)]
    pub approvals_required: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct NodePlanDto {
    pub kind: String,
    pub slug: String,
    #[serde(default)]
    pub scripts: Vec<ChangeDto>,
    #[serde(default)]
    pub routes: Vec<ChangeDto>,
    #[serde(default)]
    pub triggers: Vec<ChangeDto>,
    #[serde(default)]
    pub secrets: Vec<ChangeDto>,
    #[serde(default)]
    pub vars: Vec<ChangeDto>,
    #[serde(default)]
    pub extension_points: Vec<ChangeDto>,
    #[serde(default)]
    pub collections: Vec<ChangeDto>,
    #[serde(default)]
    pub suppressions: Vec<ChangeDto>,
    #[serde(default)]
    pub workflows: Vec<ChangeDto>,
    #[serde(default)]
    pub interceptors: Vec<ChangeDto>,
    /// §7 M3: this node's ownership outcome under the tree's `[project]`.
    #[serde(default)]
    pub ownership: Option<OwnershipPreviewDto>,
    /// §6 M2: for a group node, its structural state (in-sync omitted; diverged
    /// names the server + manifest parents).
    #[serde(default)]
    pub structure: Option<StructurePreviewDto>,
    /// Desired-state warnings this node's apply would emit, previewed at plan.
    #[serde(default)]
    pub warnings: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct StructurePreviewDto {
    pub status: String,
    #[serde(default)]
    pub server_parent: Option<String>,
    #[serde(default)]
    pub manifest_parent: Option<String>,
}

/// Response of `POST .../apply`: counts of what changed.
#[derive(Debug, Default, Deserialize)]
pub struct ApplyReportDto {
    #[serde(default)]
    pub scripts_created: u32,
    #[serde(default)]
    pub scripts_updated: u32,
    #[serde(default)]
    pub scripts_deleted: u32,
    #[serde(default)]
    pub routes_created: u32,
    #[serde(default)]
    pub routes_updated: u32,
    #[serde(default)]
    pub routes_deleted: u32,
    #[serde(default)]
    pub triggers_created: u32,
    #[serde(default)]
    pub triggers_deleted: u32,
    #[serde(default)]
    pub vars_created: u32,
    #[serde(default)]
    pub vars_updated: u32,
    #[serde(default)]
    pub vars_deleted: u32,
    #[serde(default)]
    pub extension_points_created: u32,
    #[serde(default)]
    pub extension_points_deleted: u32,
    #[serde(default)]
    pub collections_created: u32,
    #[serde(default)]
    pub collections_deleted: u32,
    #[serde(default)]
    pub suppressions_created: u32,
    #[serde(default)]
    pub suppressions_deleted: u32,
    #[serde(default)]
    pub workflows_created: u32,
    #[serde(default)]
    pub workflows_updated: u32,
    #[serde(default)]
    pub workflows_deleted: u32,
    #[serde(default)]
    pub interceptors_created: u32,
    #[serde(default)]
    pub interceptors_updated: u32,
    #[serde(default)]
    pub interceptors_deleted: u32,
    #[serde(default)]
    pub warnings: Vec<String>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct AuthMeDto {
    // Part of the wire shape (and kept for symmetry with the dashboard's
    // MeDto), even though the CLI never displays it.
    pub id: String,
    pub username: String,
    pub instance_role: InstanceRole,
    #[serde(default)]
    pub email: Option<String>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct AppLookupDto {
    #[serde(flatten)]
    pub app: App,
    // Not surfaced yet — `pic apps ls` only shows what `apps_list` returns.
    // Kept on the DTO so future `pic apps inspect <slug>` work is one-line.
    #[serde(default)]
    pub my_role: Option<AppRole>,
}

#[derive(Debug, Serialize)]
pub struct CreateAppBody<'a> {
    pub slug: &'a str,
    pub name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<&'a str>,
    /// Parent group (slug or id); omit for the instance root.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub group: Option<&'a str>,
}

#[derive(Debug, Serialize)]
pub struct CreateGroupBody<'a> {
    pub slug: &'a str,
    pub name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<&'a str>,
    /// Parent group (slug or id); omit for a root-level group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent: Option<&'a str>,
}

/// `GET /groups/{id}` response — the group plus its breadcrumb path and
/// direct children.
#[derive(Debug, Deserialize)]
pub struct GroupDetailDto {
    #[serde(flatten)]
    pub group: Group,
    pub path: Vec<Group>,
    pub subgroups: Vec<Group>,
    pub apps: Vec<App>,
}

/// One row of `pic groups ls`: a group plus its §7 owning project's slug
/// (`None` = unclaimed / UI-owned). The group fields flatten in, so `.group.*`
/// reaches them.
#[derive(Debug, Deserialize)]
pub struct GroupListItem {
    #[serde(flatten)]
    pub group: Group,
    #[serde(default)]
    pub owner: Option<String>,
}

/// One row of `pic projects ls` (§7 M3): a project + how many group nodes it
/// owns.
#[derive(Debug, Deserialize)]
pub struct ProjectDto {
    pub slug: String,
    pub name: String,
    #[serde(default)]
    pub owned_groups: i64,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Serialize)]
pub struct CreateRouteBody<'a> {
    pub host_kind: HostKind,
    #[serde(skip_serializing_if = "str::is_empty")]
    pub host: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub host_param_name: Option<&'a str>,
    pub path_kind: PathKind,
    pub path: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<&'a str>,
    pub dispatch_mode: DispatchMode,
}

#[derive(Debug, Serialize)]
pub struct CheckRouteBody {
    pub app_id: AppId,
    pub host_kind: HostKind,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub host: String,
    pub path_kind: PathKind,
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct CheckRouteResponseDto {
    pub ok: bool,
    #[serde(default)]
    pub conflicting_route: Option<Route>,
    #[serde(default)]
    pub conflict_reason: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct MatchRouteBody<'a> {
    pub app_id: AppId,
    pub url: &'a str,
    pub method: &'a str,
}

#[derive(Debug, Deserialize)]
pub struct MatchRouteResponseDto {
    #[serde(default)]
    pub matched: Option<MatchedRouteDto>,
}

#[derive(Debug, Deserialize)]
pub struct MatchedRouteDto {
    pub route_id: String,
    pub script_id: ScriptId,
    #[serde(default)]
    pub params: BTreeMap<String, String>,
    #[serde(default)]
    pub rest: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct CreateAdminBody<'a> {
    pub username: &'a str,
    pub password: &'a str,
    pub instance_role: InstanceRole,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<&'a str>,
}

#[derive(Debug, Default, Serialize)]
pub struct PatchAdminBody<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instance_role: Option<InstanceRole>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct AdminDto {
    pub id: AdminUserId,
    pub username: String,
    pub is_active: bool,
    pub instance_role: InstanceRole,
    #[serde(default)]
    pub email: Option<String>,
    pub created_at: DateTime<Utc>,
    #[serde(default)]
    pub last_login_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Deserialize)]
pub struct TriggerListDto {
    pub triggers: Vec<TriggerDto>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct TriggerDto {
    pub id: String,
    pub app_id: AppId,
    pub script_id: ScriptId,
    pub kind: String,
    pub enabled: bool,
    pub dispatch_mode: String,
    pub retry_max_attempts: u32,
    /// §4.5 M5: true for a materialized copy of a group stateful template
    /// (inherited, read-only). `default` so an older server without the field
    /// still deserializes.
    #[serde(default)]
    pub materialized: bool,
    pub created_at: DateTime<Utc>,
    #[serde(default)]
    pub details: Value,
}

/// Topic registry row. The server's `Topic` derives only `Serialize`,
/// so the CLI carries its own `Deserialize` mirror (same wire shape).
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct TopicDto {
    pub name: String,
    pub external_subscribable: bool,
    /// `public` | `token` | `session`.
    pub auth_mode: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Deserialize)]
struct TopicListDto {
    topics: Vec<TopicDto>,
}

#[derive(Debug, Deserialize)]
struct ListUsersResponseDto {
    users: Vec<AppUser>,
    // `next_cursor` exists on the wire but the CLI's `ls` is single-page
    // (--limit); pagination is a follow-up.
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct ResetPasswordResponseDto {
    pub token: String,
    pub expires_in_seconds: i64,
}

#[derive(Debug, Deserialize)]
pub struct RevokeSessionsResponseDto {
    pub revoked: u64,
}

#[derive(Debug, Deserialize)]
pub struct DeadLetterCountDto {
    pub unresolved: i64,
}

#[derive(Debug, Deserialize)]
pub struct DeadLetterListDto {
    pub dead_letters: Vec<DeadLetterDto>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct DeadLetterDto {
    pub id: String,
    pub app_id: AppId,
    pub source: String,
    pub op: String,
    pub trigger_id: Option<String>,
    pub script_id: Option<ScriptId>,
    pub payload: Value,
    pub attempt_count: u32,
    pub first_attempt_at: DateTime<Utc>,
    pub last_attempt_at: DateTime<Utc>,
    pub last_error: String,
    pub created_at: DateTime<Utc>,
    pub resolved_at: Option<DateTime<Utc>>,
    pub resolution: Option<String>,
}

/// Which owner a `pic vars` call targets. Selects the `apps` vs `groups`
/// admin path prefix; the identifier travels in the path (encoded).
#[derive(Debug, Clone, Copy)]
pub enum VarOwnerArg<'a> {
    App(&'a str),
    Group(&'a str),
}

impl VarOwnerArg<'_> {
    fn base_path(&self) -> String {
        match self {
            Self::App(ident) => format!("/api/v1/admin/apps/{}", seg(ident)),
            Self::Group(ident) => format!("/api/v1/admin/groups/{}", seg(ident)),
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct VarListDto {
    pub vars: Vec<VarItemDto>,
}

#[derive(Debug, Deserialize)]
pub struct VarItemDto {
    pub key: String,
    pub env: String,
    pub value: serde_json::Value,
    pub is_tombstone: bool,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Deserialize)]
pub struct SecretListDto {
    pub secrets: Vec<SecretItemDto>,
    #[serde(default)]
    #[allow(dead_code)]
    pub next_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SecretItemDto {
    pub name: String,
    /// Env scope. Only meaningful (and populated) for group owners; the server
    /// omits it for app secrets, so default to `*` when absent.
    #[serde(default = "default_env")]
    pub env: String,
    pub updated_at: DateTime<Utc>,
}

fn default_env() -> String {
    "*".to_string()
}

/// Plaintext value of a single group secret — the response of the gated
/// `.../secrets/{name}/value` read. The decrypted value is arbitrary JSON.
#[derive(Debug, Deserialize)]
pub struct SecretValueDto {
    #[allow(dead_code)]
    pub name: String,
    #[allow(dead_code)]
    pub env: String,
    pub value: serde_json::Value,
}

// --- effective config (`/config/effective`) ---

/// The owner (app or group) a resolved layer belongs to, with its distance
/// from the app in the inheritance chain (`depth` 0 = the app itself).
#[derive(Debug, Deserialize)]
pub struct EffectiveOwnerDto {
    pub kind: String,
    #[allow(dead_code)]
    pub id: String,
    pub depth: u32,
}

/// One layer a resolved var merged from, deepest-first as the server returns it.
#[derive(Debug, Deserialize)]
pub struct MergedFromDto {
    pub depth: u32,
    pub scope: String,
}

#[derive(Debug, Deserialize)]
pub struct EffectiveVarDto {
    pub value: serde_json::Value,
    pub owner: EffectiveOwnerDto,
    pub scope: String,
    #[serde(default)]
    pub merged_from: Vec<MergedFromDto>,
}

#[derive(Debug, Deserialize)]
pub struct EffectiveSecretDto {
    #[allow(dead_code)]
    pub status: String,
    pub owner: EffectiveOwnerDto,
    pub scope: String,
}

#[derive(Debug, Deserialize)]
pub struct EffectiveConfigDto {
    #[serde(default)]
    pub vars: std::collections::BTreeMap<String, EffectiveVarDto>,
    #[serde(default)]
    pub secrets: std::collections::BTreeMap<String, EffectiveSecretDto>,
}

/// Per-script runtime config the CLI can now set (G3). All optional — an
/// unset field is omitted so the server applies its own default (and the
/// `PICLOUD_SANDBOX_MAX_*` admin ceilings still clamp overrides).
#[derive(Debug, Default, Clone)]
pub struct ScriptConfig {
    pub timeout_seconds: Option<i32>,
    pub memory_limit_mb: Option<i32>,
    pub kind: Option<ScriptKind>,
    pub sandbox: Option<ScriptSandbox>,
}

#[derive(Debug, Serialize)]
pub struct CreateScriptBody<'a> {
    pub app_id: AppId,
    pub name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<&'a str>,
    pub source: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_mb: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<ScriptKind>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<ScriptSandbox>,
}

/// Phase 4: body for `POST /groups/{id}/scripts`. Like `CreateScriptBody`
/// minus `app_id` — the owning group comes from the path.
#[derive(Debug, Serialize)]
pub struct CreateGroupScriptBody<'a> {
    pub name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<&'a str>,
    pub source: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout_seconds: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub memory_limit_mb: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<ScriptKind>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox: Option<ScriptSandbox>,
}

#[derive(Debug, Serialize)]
struct UpdateScriptBody<'a> {
    source: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    timeout_seconds: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    memory_limit_mb: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    kind: Option<ScriptKind>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sandbox: Option<ScriptSandbox>,
}

// --- G2 response DTOs (deserialize-only mirrors of the server shapes) ---

// `#[allow(dead_code)]` on a couple of fields below: these structs mirror
// the full server response shape (so the surface is documented and future
// columns are a one-line add), but the TSV/KvBlock renderers don't print
// every field today.

#[derive(Debug, Deserialize)]
pub struct WorkflowDto {
    pub name: String,
    pub enabled: bool,
    pub steps: usize,
    /// The full stored definition — present so `pic pull` can rebuild the
    /// `[[workflows]]` manifest block. `#[serde(default)]` tolerates an older
    /// server that predates the field (the definition is then empty).
    #[serde(default = "empty_workflow_definition")]
    pub definition: picloud_shared::WorkflowDefinition,
}

fn empty_workflow_definition() -> picloud_shared::WorkflowDefinition {
    picloud_shared::WorkflowDefinition { steps: Vec::new() }
}

#[derive(Debug, Deserialize)]
pub struct WorkflowRunDto {
    pub id: String,
    pub status: String,
    #[serde(default)]
    pub error: Option<String>,
    pub workflow_depth: i32,
    pub created_at: String,
}

#[derive(Debug, Deserialize)]
pub struct WorkflowRunStepDto {
    pub name: String,
    pub status: String,
    pub attempt: i32,
    pub max_attempts: i32,
    #[serde(default)]
    pub error: Option<String>,
    #[serde(default)]
    pub child_run_id: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct WorkflowRunDetailDto {
    pub run: WorkflowRunDto,
    pub steps: Vec<WorkflowRunStepDto>,
}

#[derive(Debug, Deserialize)]
pub struct AppMemberDto {
    pub user_id: AdminUserId,
    pub username: String,
    #[allow(dead_code)]
    pub email: Option<String>,
    pub instance_role: InstanceRole,
    pub is_active: bool,
    pub role: AppRole,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Deserialize)]
pub struct FileMetaDto {
    pub id: String,
    #[allow(dead_code)]
    pub collection: String,
    pub name: String,
    pub content_type: String,
    pub size: u64,
    #[allow(dead_code)]
    pub checksum: String,
    #[allow(dead_code)]
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Deserialize)]
pub struct ListFilesResponse {
    pub files: Vec<FileMetaDto>,
    pub next_cursor: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct KvListPageDto {
    pub keys: Vec<String>,
    pub next_cursor: Option<String>,
}

/// One document in a group's shared-docs collection (operator listing). The
/// server also sends each doc's `data`, but the `ls` view shows ids only (fetch
/// a document's body with `pic docs get`), so it is not deserialized here.
#[derive(Debug, Deserialize)]
pub struct GroupDocEntryDto {
    pub id: String,
}

#[derive(Debug, Deserialize)]
pub struct GroupDocsListDto {
    pub docs: Vec<GroupDocEntryDto>,
    pub next_cursor: Option<String>,
}

/// One group shared-queue dead-letter (operator listing). Distinct from the
/// per-app `DeadLetterDto`: a group DL carries no `app_id`/`trigger_id` and
/// includes the `collection` it belonged to; timestamps are RFC3339 strings.
#[derive(Debug, Deserialize)]
pub struct GroupDeadLetterDto {
    pub id: String,
    pub collection: String,
    pub source: String,
    pub op: String,
    pub attempt_count: u32,
    pub last_error: String,
    pub created_at: String,
    pub resolved_at: Option<String>,
    #[allow(dead_code)]
    pub payload: Value,
}

#[derive(Debug, Deserialize)]
struct KvGetResponse {
    value: Value,
}

#[derive(Debug, Deserialize)]
pub struct QueueSummaryDto {
    pub queue_name: String,
    pub total: u64,
    pub pending: u64,
    pub claimed: u64,
}

#[derive(Debug, Deserialize)]
pub struct QueueConsumerDto {
    pub trigger_id: String,
    pub script_id: ScriptId,
    pub script_name: String,
    pub visibility_timeout_secs: u32,
    pub last_fired_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Deserialize)]
pub struct QueueDetailDto {
    pub queue_name: String,
    pub total: u64,
    pub pending: u64,
    pub claimed: u64,
    pub consumer: Option<QueueConsumerDto>,
}

#[derive(Debug, Serialize)]
struct LoginRequestBody<'a> {
    username: &'a str,
    password: &'a str,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct LoginResponseDto {
    pub user: LoginUserDto,
    pub token: String,
    pub expires_at: DateTime<Utc>,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct LoginUserDto {
    pub id: AdminUserId,
    pub username: String,
    pub instance_role: InstanceRole,
    #[serde(default)]
    pub email: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct MintApiKeyBody<'a> {
    pub name: &'a str,
    pub scopes: &'a [Scope],
    #[serde(skip_serializing_if = "Option::is_none")]
    pub app_id: Option<AppId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<DateTime<Utc>>,
}

/// Fresh-mint response. The `raw_token` field is the one and only
/// chance to capture the bearer string; subsequent `GET /api-keys`
/// returns the `ApiKeyDto` portion without it.
#[derive(Debug, Deserialize)]
pub struct MintApiKeyResponseDto {
    #[serde(flatten)]
    pub key: ApiKeyDto,
    pub raw_token: String,
}

#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct ApiKeyDto {
    pub id: ApiKeyId,
    pub prefix: String,
    pub name: String,
    pub scopes: Vec<Scope>,
    pub app_id: Option<AppId>,
    pub expires_at: Option<DateTime<Utc>>,
    pub last_used_at: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct ExecuteResponse {
    pub status_code: u16,
    // Captured for completeness; not displayed today, but `pic invoke -v`
    // could surface them later without changing this struct.
    pub headers: BTreeMap<String, String>,
    pub body: Value,
}

// ---------- helpers ----------

/// Parse `-H "Key: value"` or `-H "Key=value"` into a `(name, value)`
/// pair. Trims surrounding whitespace on both sides.
pub fn parse_kv_header(raw: &str) -> Result<(String, String), String> {
    let (k, v) = raw
        .split_once(':')
        .or_else(|| raw.split_once('='))
        .ok_or_else(|| format!("expected `Key: value` or `Key=value`, got {raw:?}"))?;
    let k = k.trim();
    let v = v.trim();
    if k.is_empty() {
        return Err(format!("empty header name in {raw:?}"));
    }
    Ok((k.to_string(), v.to_string()))
}

fn urlencoded(s: &str) -> String {
    // Minimal pass: percent-encode the few chars that break the query.
    // Slugs and UUIDs don't contain them in practice, but be safe.
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' | '=' | '?' | '#' | ' ' => {
                out.push_str(&format!("%{:02X}", u32::from(ch)));
            }
            _ => out.push(ch),
        }
    }
    out
}

async fn decode<T: for<'de> Deserialize<'de>>(resp: reqwest::Response) -> Result<T> {
    if resp.status().is_success() {
        return resp.json::<T>().await.context("parsing response body");
    }
    Err(server_error(resp).await)
}

/// Like `decode` but for endpoints whose 2xx response has no body
/// (204 No Content) — DELETE handlers, logout.
async fn decode_status(resp: reqwest::Response) -> Result<()> {
    if resp.status().is_success() {
        return Ok(());
    }
    Err(server_error(resp).await)
}

async fn server_error(resp: reqwest::Response) -> anyhow::Error {
    let status = resp.status();
    let body = resp.text().await.unwrap_or_default();
    let msg = parse_error_body(&body).unwrap_or(body);
    let hint = role_hint(status);
    if hint.is_empty() {
        anyhow!("HTTP {}: {}", status.as_u16(), msg)
    } else {
        anyhow!("HTTP {}: {} ({})", status.as_u16(), msg, hint)
    }
}

fn parse_error_body(s: &str) -> Option<String> {
    let v: Value = serde_json::from_str(s).ok()?;
    let obj = v.as_object()?;
    if let Some(m) = obj.get("message").and_then(Value::as_str) {
        return Some(m.to_string());
    }
    if let Some(e) = obj.get("error").and_then(Value::as_str) {
        return Some(e.to_string());
    }
    None
}

fn role_hint(status: StatusCode) -> &'static str {
    match status {
        StatusCode::FORBIDDEN => "your role may lack the required capability; check `pic whoami`",
        StatusCode::UNAUTHORIZED => "token rejected; re-run `pic login`",
        _ => "",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_kv_colon() {
        let (k, v) = parse_kv_header("X-Foo: bar").unwrap();
        assert_eq!(k, "X-Foo");
        assert_eq!(v, "bar");
    }

    #[test]
    fn parse_kv_equals() {
        let (k, v) = parse_kv_header("X-Foo=bar").unwrap();
        assert_eq!(k, "X-Foo");
        assert_eq!(v, "bar");
    }

    #[test]
    fn parse_kv_rejects_no_separator() {
        assert!(parse_kv_header("X-Foo").is_err());
    }

    #[test]
    fn parse_kv_rejects_empty_name() {
        assert!(parse_kv_header(": bar").is_err());
    }

    #[test]
    fn url_strip_trailing_slash() {
        let c = Client::new("http://localhost:8000/", "pic_x").unwrap();
        assert_eq!(c.url(), "http://localhost:8000");
    }

    #[test]
    fn seg_escapes_path_delimiters() {
        // A free-form segment can't break out into a new path segment,
        // the query, or the fragment.
        assert_eq!(seg("a/b"), "a%2Fb");
        assert_eq!(seg("a?b"), "a%3Fb");
        assert_eq!(seg("a#b"), "a%23b");
        assert_eq!(seg("a b"), "a%20b");
        // Ordinary slugs / UUIDs pass through unchanged.
        assert_eq!(seg("my-app"), "my-app");
        assert_eq!(
            seg("4c8b8775-2a9e-4212-9187-a8f56a1b60e7"),
            "4c8b8775-2a9e-4212-9187-a8f56a1b60e7"
        );
    }
}
