#!/usr/bin/env bash
# Tests de bout en bout : audits WC/Umami + rapports + cohérence CA.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${DEPLOY_ENV:-$ROOT/.secrets/.env}"
DAYS="${1:-90}"
SSH_KEY="${SSH_PRIVATE_KEY_FILE:-$HOME/.ssh/amssh}"
SSH_USER="${DEPLOY_USER:-sc1mear8437}"
SSH_HOST="${DEPLOY_HOST:-sc1mear8437.universe.wf}"

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

export UMAMI_ADMIN_USER="${UMAMI_ADMIN_USER:-${UMAMI_SITE_ID:-admin}}"
export UMAMI_ADMIN_PASSWORD="${UMAMI_ADMIN_PASSWORD:-${UMAMI_SITE_PASSWORD:-}}"

if [[ -z "${UMAMI_ADMIN_PASSWORD:-}" ]]; then
	echo "UMAMI_SITE_PASSWORD manquant dans $ENV_FILE" >&2
	exit 1
fi

echo "=== WooCommerce (${DAYS}j) ==="
WC_JSON="$(ssh -4 -i "$SSH_KEY" "${SSH_USER}@${SSH_HOST}" \
	"cd /home/sc1mear8437/public_html && php scripts/audit-wc-wp-stats.php ${DAYS}")"
echo "$WC_JSON" | python3 -c "import json,sys; d=json.load(sys.stdin); wc=d['woocommerce']; print('commandes=%s CA=%s EUR trackées=%s' % (wc['orders_total'], wc['revenue_eur'], wc['tracked_umami']))"

echo ""
echo "=== Umami (${DAYS}j) ==="
UMAMI_JSON="$(python3 "$ROOT/scripts/audit-umami-reports.py" "$DAYS")"

python3 -c '
import json, sys
wc = json.loads(sys.argv[1])
umami = json.loads(sys.argv[2])
events = {e.get("x"): e.get("y") for e in umami.get("events", [])}
print("événements:", ", ".join(f"{k}={v}" for k, v in sorted(events.items())))
rev = umami.get("reports", {}).get("Chiffre d'\''affaires", {}).get("data", {})
if isinstance(rev, dict) and rev.get("total"):
    umami_rev = float(rev["total"].get("sum", 0))
    umami_cnt = int(rev["total"].get("count", 0))
else:
    umami_rev = 0
    umami_cnt = events.get("purchase", 0)
wc_rev = wc["woocommerce"]["revenue_eur"]
wc_cnt = wc["woocommerce"]["orders_total"]
print(f"CA Umami={umami_rev:.2f} EUR ({umami_cnt}) vs WC={wc_rev:.2f} EUR ({wc_cnt})")
errors = [name for name, r in umami.get("reports", {}).items() if r.get("error")]
if errors:
    print("rapports en erreur:", ", ".join(errors))
    sys.exit(1)
print("tous les rapports OK")
' "$WC_JSON" "$UMAMI_JSON"

echo ""
echo "=== Vérification page article (view_blog_post) ==="
POST_URL="$(ssh -4 -i "$SSH_KEY" "${SSH_USER}@${SSH_HOST}" \
	"cd /home/sc1mear8437/public_html && php -r 'require \"www/wp-load.php\"; \$p=get_posts([\"numberposts\"=>1]); echo get_permalink(\$p[0]);'")"
HTML="$(curl -sfL "$POST_URL")"
if echo "$HTML" | grep -q 'numberone-umami-events.js'; then
	echo "tracker JS présent sur $POST_URL"
else
	echo "ERREUR: tracker JS absent sur $POST_URL" >&2
	exit 1
fi
if echo "$HTML" | grep -q '"type":"blog"'; then
	echo "config page.type=blog OK"
else
	echo "AVERTISSEMENT: post_id blog non détecté dans numberoneUmamiConfig"
fi

echo ""
echo "Tests terminés avec succès."
