---
name: ci-deploy-status
description: >
  Check the deployment status of an environment (review, dev, prod) by cross-referencing
  GitLab environments, CI pipeline jobs, and live Kubernetes pods.
  Use when the user says /ci-deploy-status, 'est-ce que la review est deployee',
  'url de la review', 'status du deploy', 'est-ce deployé en prod',
  or when delegated from /glab-mr-approve to verify deployment status.
argument-hint: "<environment: review (default), dev, prod> [optional: MR !IID or app name]"
allowed-tools:
  - Bash
  - mcp__kubernetes__kubectl_get
  - mcp__kubernetes__kubectl_describe
---

Check whether an environment is deployed by cross-referencing three sources: GitLab environments, CI pipeline jobs, and live Kubernetes pod state.

**IMPORTANT — show the URL and status to the user as fast as possible.** Start with the GitLab environment (fastest), display the result immediately, then enrich with CI and K8s details.

## Required tools

- `glab`
- `kubectl`

Run `pysae-ai-tools tools require <tools>` before starting; if it exits non-zero, abort and report the install command from stderr to the user.

## Phase 1 : Quick answer (display immediately)

1. **Determine target environment** — parse `$ARGUMENTS`:
   - `review` (default) — review environment for the current MR
   - `dev` — development environment
   - `prod` — production environment

2. **Resolve project context**:
   ```bash
   CTX=$(pysae-ai-tools internal detect-context)
   PROJECT_ID=$(echo "$CTX" | jq -r '.project_id // empty')
   PROJECT_URL=$(echo "$CTX" | jq -r '.project_url // empty')
   MR_IID=$(echo "$CTX" | jq -r '.mr_iid // empty')
   MR_SOURCE_BRANCH=$(echo "$CTX" | jq -r '.mr_source_branch // empty')
   ```
   For review environments, use `MR_SOURCE_BRANCH` as the branch name for environment lookup.

3. **Query GitLab environment** — this is the fastest source, query it first:

   ### Review
   Use the branch name as search term and filter by `states=available` for fast lookup:
   ```bash
   ENV_DATA=$(glab api "projects/${PROJECT_ID}/environments?search=${MR_SOURCE_BRANCH}&states=available&per_page=50" \
     | jq --arg branch "$MR_SOURCE_BRANCH" --arg iid "$MR_IID" \
       '[.[] | select(.name | test("review.*(" + $branch + "|" + $iid + ")"))] | first // empty')
   ```

   ### Dev / Prod
   ```bash
   ENV_DATA=$(glab api "projects/${PROJECT_ID}/environments?search=<app>-<env>&per_page=10" \
     | jq '[.[] | select(.state == "available")] | first // empty')
   ```

   Extract and **display immediately**:
   ```bash
   ENV_URL=$(echo "$ENV_DATA" | jq -r '.external_url // empty')
   ENV_STATE=$(echo "$ENV_DATA" | jq -r '.state // empty')  # available, stopped, stopping
   ```

   **Print the URL and status now** — do not wait for the other sources. Example:
   > **Review** : `available` — https://review-feat-123.example.com
   >
   > or
   >
   > **Review** : `stopped` (environnement arrete)
   >
   > or
   >
   > **Review** : aucun environnement trouve

## Phase 2 : Detailed diagnostics (after displaying URL)

After the quick answer is shown, enrich with deeper checks:

### CI pipeline deploy job

Check the latest pipeline for a deploy job:
```bash
# Review: MR pipeline
PIPELINE_ID=$(glab api "projects/${PROJECT_ID}/merge_requests/${MR_IID}/pipelines" | jq -r '.[0].id // empty')
# Dev/Prod: branch or tag pipeline
PIPELINE_ID=$(glab api "projects/${PROJECT_ID}/pipelines?ref=<ref>&per_page=1" | jq -r '.[0].id // empty')

DEPLOY_JOB=$(glab api "projects/${PROJECT_ID}/pipelines/${PIPELINE_ID}/jobs?per_page=100&include_retried=false" \
  | jq -r --arg env "$TARGET_ENV" '[.[] | select(.name | test("deploy.*" + $env))] | first // empty')
JOB_STATUS=$(echo "$DEPLOY_JOB" | jq -r '.status // empty')
```

### Kubernetes pod state

Verify live state on the cluster. Use the app-to-K8s mapping from `/ci-deploy` (Step 0 table) to resolve the deployment name and namespace.

```bash
kubectl get pods -n <namespace> -l app=<deployment-name> --no-headers
```

Check:
- All pods `Running` + `Ready` → healthy
- `CrashLoopBackOff`, `Error`, `OOMKilled` → broken
- No pods → not deployed or scaled to zero

**Deployed version** (image tag):
```bash
kubectl get deployment <deployment-name> -n <namespace> \
  -o jsonpath='{.spec.template.spec.containers[0].image}'
```

**Rollout status** (in progress or complete?):
```bash
kubectl rollout status deployment/<deployment-name> -n <namespace> --timeout=5s
```
- Exit code 0 → rollout complete
- Non-zero / timeout → rollout in progress or stuck

## Verdict

Cross-reference all three sources and append the final verdict after the quick answer:

| GitLab env          | CI job              | K8s pods        | Verdict              |
|---------------------|---------------------|-----------------|----------------------|
| `available` + URL   | `success`           | Running + Ready | `DEPLOYED`           |
| `available` + URL   | `success`           | CrashLoop/Error | `DEPLOYED_UNHEALTHY` |
| any                 | `running`/`pending` | any             | `DEPLOYING`          |
| any                 | `manual`/`created`  | no pods         | `NOT_DEPLOYED`       |
| any                 | `failed`            | any             | `DEPLOY_FAILED`      |
| `stopped`           | any                 | no pods         | `STOPPED`            |
| none                | none                | no pods         | `NO_DEPLOY_JOB`     |
| any                 | any                 | Running + Ready | `DEPLOYED`           |
| —                   | —                   | —               | `NO_PIPELINE`        |
| — (review)          | —                   | —               | `NO_MR`              |

## Output

Display in two passes:

**Pass 1 (immediate):** URL + GitLab environment status

**Pass 2 (enrichment):** append CI job status, K8s pod health (count running/total), image tag, rollout status, pipeline link. Flag any discrepancies (e.g. GitLab says `available` but pods are crashing).

$ARGUMENTS
