#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "${REPO_ROOT}/scripts/cluster-env.sh"

NAMESPACE="${ARGOCD_NAMESPACE:-argocd}"
KUBECONFIG_PATH="${KUBECONFIG_PATH:-${LAB_KUBECONFIG_PATH:-${KUBECONFIG:-/home/jv/.kube/config}}}"
APP="${1:-}"

if [[ -n "${APP}" && ! "${APP}" =~ ^[A-Za-z0-9._-]+$ ]]; then
    echo "invalid Argo CD application name: ${APP}" >&2
    exit 2
fi

if [[ -n "${APP}" ]]; then
    payload="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${NAMESPACE}" get application "${APP}" -o json)"
else
    payload="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${NAMESPACE}" get applications.argoproj.io -o json)"
fi

python3 - "${payload}" <<'PY'
import json
import sys

document = json.loads(sys.argv[1])
items = document.get("items", [document] if document.get("kind") == "Application" else [])
if not items:
    print("No Argo CD Applications found.")
    raise SystemExit(0)

drift = False
for app in items:
    metadata = app.get("metadata", {})
    spec = app.get("spec", {})
    status = app.get("status", {})
    name = metadata.get("name", "unknown")
    sync = status.get("sync", {}).get("status", "Unknown")
    health = status.get("health", {}).get("status", "Unknown")
    revision = status.get("sync", {}).get("revision", "")
    path = spec.get("source", {}).get("path", "")
    resources = status.get("resources", [])
    changed = [
        f"{item.get('kind','?')}/{item.get('name','?')}:{item.get('status','?')}"
        for item in resources
        if item.get("status") not in (None, "Synced") or item.get("health", {}).get("status") not in (None, "Healthy")
    ]
    if sync != "Synced" or changed:
        drift = True
    print(f"{name}: sync={sync} health={health} revision={revision or '-'} path={path or '-'}")
    if changed:
        print("  resources: " + ", ".join(changed))
    conditions = status.get("conditions", [])
    for condition in conditions[-3:]:
        message = condition.get("message")
        if message:
            print(f"  condition: {message}")
print(f"Drift detected: {'yes' if drift else 'no'}")
PY
