#!/usr/bin/env bash
# Génère le client OAuth « Cursor » (projet latoutfrancais) depuis .secrets/.env
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="${ROOT}/.secrets/.env"
OUT_JSON="${HOME}/.config/gcloud/cursor-latoutfrancais-oauth-client.json"
GSC_CONFIG_DIR="${HOME}/Library/Preferences/gsc-mcp"
GSC_CONFIG="${GSC_CONFIG_DIR}/config.json"
GCP_PROJECT="latoutfrancais"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Fichier introuvable : ${ENV_FILE}" >&2
  exit 1
fi

read_env() {
  local key="$1"
  local val
  val="$(grep -E "^${key}=" "$ENV_FILE" | head -1 | cut -d= -f2- | tr -d '\r')"
  if [[ -z "$val" ]]; then
    echo "Variable manquante dans .secrets/.env : ${key}" >&2
    exit 1
  fi
  printf '%s' "$val"
}

CLIENT_ID="$(read_env GOOGLE_ID_CLIENT)"
CLIENT_SECRET="$(read_env GOOGLE_SECRET)"
PILOTECOM_WEB_CLIENT="1043449182389-kbif4h7m607a2va71p0ck51ohr0cqign.apps.googleusercontent.com"

if [[ "$CLIENT_ID" == "$PILOTECOM_WEB_CLIENT" ]]; then
  echo "ERREUR : GOOGLE_ID_CLIENT = client OAuth PilotEcom (app web)." >&2
  echo "Dans GCP latoutfrancais → Credentials, copie le client Desktop « Cursor », pas PilotEcom Web." >&2
  exit 1
fi

mkdir -p "$(dirname "$OUT_JSON")" "$GSC_CONFIG_DIR"

python3 - "$OUT_JSON" "$GCP_PROJECT" "$CLIENT_ID" "$CLIENT_SECRET" <<'PY'
import json, sys
out, project, cid, secret = sys.argv[1:5]
payload = {
    "installed": {
        "client_id": cid,
        "project_id": project,
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": secret,
        "redirect_uris": ["http://localhost"],
    }
}
with open(out, "w", encoding="utf-8") as f:
    json.dump(payload, f, indent=2)
    f.write("\n")
PY

python3 - "$GSC_CONFIG" "$CLIENT_ID" "$CLIENT_SECRET" <<'PY'
import json, sys
path, cid, secret = sys.argv[1:4]
with open(path, "w", encoding="utf-8") as f:
    json.dump(
        {
            "clientId": cid,
            "clientSecret": secret,
            "authType": "oauth",
            "scope": "readonly",
        },
        f,
        indent=2,
    )
    f.write("\n")
PY

chmod 600 "$OUT_JSON" "$GSC_CONFIG"
echo "OK — client OAuth Cursor (latoutfrancais)"
echo "  ADC : ${OUT_JSON}"
echo "  GSC : ${GSC_CONFIG}"
