#!/usr/bin/env bash
# Crée ou met à jour les rapports Umami définis dans infra/umami/reports.json.
#
# Usage :
#   ./scripts/umami-reports-bootstrap.sh
#   ./scripts/umami-reports-bootstrap.sh --update
#   ./scripts/umami-reports-bootstrap.sh https://analytics.arnaud-merigeau.fr production --update
#
# Variables (ou .secrets/.env) :
#   UMAMI_HOST, UMAMI_ADMIN_USER, UMAMI_ADMIN_PASSWORD

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${DEPLOY_ENV:-$ROOT/.secrets/.env}"
BASE_URL=""
ENV_KEY="production"
UPDATE_EXISTING=false
REPORTS_FILE="$ROOT/infra/umami/reports.json"
WEBSITES_FILE="$ROOT/infra/umami/websites.json"

while [[ $# -gt 0 ]]; do
	case "$1" in
		--update) UPDATE_EXISTING=true; shift ;;
		--env) ENV_FILE="$2"; shift 2 ;;
		-h|--help)
			sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'
			exit 0
			;;
		*)
			if [[ -z "$BASE_URL" ]]; then
				BASE_URL="$1"
			elif [[ "$ENV_KEY" == "production" && "$1" != "production" && "$1" != "local" ]]; then
				ENV_KEY="$1"
			else
				ENV_KEY="$1"
			fi
			shift
			;;
	esac
done

if [[ -f "$ENV_FILE" ]]; then
	while IFS= read -r line || [[ -n "$line" ]]; do
		line="${line%%#*}"
		line="${line#"${line%%[![:space:]]*}"}"
		line="${line%"${line##*[![:space:]]}"}"
		[[ -n "$line" ]] || continue
		[[ "$line" == UMAMI_* ]] || continue
		key="${line%%=*}"
		val="${line#*=}"
		export "$key=$val"
	done < "$ENV_FILE"
fi

BASE_URL="${BASE_URL:-${UMAMI_HOST:-}}"
USER="${UMAMI_ADMIN_USER:-${UMAMI_SITE_ID:-admin}}"
PASS="${UMAMI_ADMIN_PASSWORD:-${UMAMI_SITE_PASSWORD:-umami}}"

if [[ -z "$BASE_URL" ]]; then
	echo "URL Umami manquante (UMAMI_HOST ou argument 1)." >&2
	exit 1
fi

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

WEBSITE_ID="$(python3 - "$WEBSITES_FILE" "$ENV_KEY" <<'PY'
import json, sys
path, env_key = sys.argv[1:3]
with open(path, encoding='utf-8') as fh:
    data = json.load(fh)
print(data.get(env_key, {}).get('website_id', ''))
PY
)"

if [[ -z "$WEBSITE_ID" ]]; then
	echo "website_id absent pour « $ENV_KEY » dans $WEBSITES_FILE" >&2
	exit 1
fi

echo "Connexion Umami ($BASE_URL)…"
TOKEN="$(curl -sf "${BASE_URL}/api/auth/login" \
	-H 'Content-Type: application/json' \
	-d "{\"username\":\"${USER}\",\"password\":\"${PASS}\"}" \
	| python3 -c 'import json,sys; print(json.load(sys.stdin).get("token",""))')"

if [[ -z "$TOKEN" ]]; then
	echo "Échec login Umami." >&2
	exit 1
fi

EXISTING="$(curl -sf "${BASE_URL}/api/reports?websiteId=${WEBSITE_ID}&pageSize=100" \
	-H "Authorization: Bearer ${TOKEN}")"

UPDATE_FLAG="$UPDATE_EXISTING" REPORTS_FILE="$REPORTS_FILE" WEBSITE_ID="$WEBSITE_ID" BASE_URL="$BASE_URL" TOKEN="$TOKEN" EXISTING_JSON="$EXISTING" python3 <<'PY'
import json, os, sys, urllib.request, urllib.error

reports_path = os.environ["REPORTS_FILE"]
website_id = os.environ["WEBSITE_ID"]
base_url = os.environ["BASE_URL"]
token = os.environ["TOKEN"]
update_existing = os.environ.get("UPDATE_FLAG", "false") == "true"
existing_raw = os.environ.get("EXISTING_JSON", "{}")

with open(reports_path, encoding="utf-8") as fh:
    reports = json.load(fh)

try:
    existing_payload = json.loads(existing_raw)
except json.JSONDecodeError:
    existing_payload = {}

existing = existing_payload.get("data", existing_payload)
if not isinstance(existing, list):
    existing = []

existing_by_name = {
    item.get("name", ""): item
    for item in existing
    if isinstance(item, dict) and item.get("websiteId") == website_id
}

def build_parameters(report_params: dict) -> dict:
    return {
        "websiteId": website_id,
        "dateRange": {"value": "30day"},
        **report_params,
    }

def api_request(path: str, method: str, body: dict | None = None):
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(
        f"{base_url.rstrip('/')}{path}",
        data=data,
        headers={
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        },
        method=method,
    )
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read().decode())

created = 0
updated = 0
skipped = 0

for report in reports:
    name = report["name"]
    payload = {
        "websiteId": website_id,
        "name": name,
        "description": report.get("description", ""),
        "type": report["type"],
        "parameters": build_parameters(report.get("parameters", {})),
    }

    if name in existing_by_name:
        if not update_existing:
            print(f"  = déjà présent : {name}")
            skipped += 1
            continue
        report_id = existing_by_name[name]["id"]
        try:
            api_request(f"/api/reports/{report_id}", "POST", payload)
            print(f"  ~ mis à jour : {name}")
            updated += 1
        except urllib.error.HTTPError as err:
            detail = err.read().decode("utf-8", errors="replace")
            print(f"  ! échec mise à jour {name} ({err.code}) : {detail}", file=sys.stderr)
            sys.exit(1)
        continue

    try:
        api_request("/api/reports", "POST", payload)
        print(f"  + créé : {name}")
        created += 1
    except urllib.error.HTTPError as err:
        detail = err.read().decode("utf-8", errors="replace")
        print(f"  ! échec {name} ({err.code}) : {detail}", file=sys.stderr)
        sys.exit(1)

print(f"\nTerminé : {created} créé(s), {updated} mis à jour, {skipped} ignoré(s).")
PY
