#!/usr/bin/env bash
# update-institutions.sh — mise à jour hebdomadaire de scripts/institutions.json
# (composition Assemblée nationale, Gouvernement, Sénat) et scripts/deputes.json
# (liste des 577 députés), puis upload FTP.
# Usage: ./update-institutions.sh
set -euo pipefail

SITE_DIR="/home/alan/SITE/WEB"
CRON_DIR="/home/alan/SITE/CRON"
LOG_DIR="${CRON_DIR}/logs"
mkdir -p "${LOG_DIR}"

STAMP="$(date +%Y-%m-%d_%H-%M)"
LOG_FILE="${LOG_DIR}/institutions_${STAMP}.log"
JSON="${SITE_DIR}/scripts/institutions.json"
DEPUTES_JSON="${SITE_DIR}/scripts/deputes.json"

echo "[${STAMP}] Mise à jour des institutions → ${LOG_FILE}" >> "${LOG_DIR}/maj.log"

before_stamp=$(stat -c %Y "${JSON}" 2>/dev/null || echo 0)
before_deputes=$(stat -c %Y "${DEPUTES_JSON}" 2>/dev/null || echo 0)

MESSAGE="Lis /home/alan/SITE/WEB/AGENTS.md (règles de recherche : max 6 webfetch, max 8 steps, 3 min par page, pas de retry sur 429).
Mets à jour le fichier /home/alan/SITE/WEB/scripts/institutions.json avec la composition ACTUELLE :
1. Assemblée nationale : effectifs des groupes politiques (source : assemblee-nationale.fr)
2. Gouvernement : Premier ministre + ministres de plein exercice (source : info.gouv.fr)
3. Sénat : effectifs des groupes politiques (source : senat.fr)
Conserve EXACTEMENT la structure JSON existante (clés assemblee/gouvernement/senat, champs groupe/sieges et poste/nom).
Met à jour le champ maj au format JJ/MM/AAAA.
Si les données n'ont pas changé, ne modifie pas le fichier.
Quand tu utilises l'outil bash pour une commande réseau, spécifie timeout: 15000 dans l'appel à l'outil."

timeout 300 /home/alan/.opencode/bin/opencode run "${MESSAGE}" --print-logs --log-level WARN >> "${LOG_FILE}" 2>&1 || {
  echo "[${STAMP}] ÉCHEC institutions (voir ${LOG_FILE})" >> "${LOG_DIR}/maj.log"
  exit 1
}

# Mise à jour de deputes.json depuis le CSV officiel de l'Assemblée nationale
# (data.gouv.fr, dataset « Députés actifs de l'Assemblée nationale »)
DEPUTES_CSV_URL="https://www.data.gouv.fr/api/1/datasets/deputes-actifs-de-lassemblee-nationale-informations-et-statistiques/"
CSV_URL=$(curl -s --max-time 15 "${DEPUTES_CSV_URL}" | python3 -c "
import json,sys
d = json.load(sys.stdin)
for r in d.get('resources', []):
    if r.get('format') == 'csv':
        print(r.get('url'))
        break
" 2>/dev/null || true)

if [[ -n "${CSV_URL}" ]]; then
  curl -s --max-time 20 "${CSV_URL}" -o /tmp/opencode/deputes_an.csv
  python3 << 'PYEOF'
import csv, json

with open('/tmp/opencode/deputes_an.csv') as f:
    rows = list(csv.DictReader(f))

deputes = []
for r in rows:
    deputes.append({
        "nom": f"{r['prenom']} {r['nom']}",
        "groupe": r['groupeAbrev'],
        "circonscription": f"{r['departementNom']} ({r['circo']})"
    })

deputes.sort(key=lambda x: x['nom'])
from datetime import date
data = {"maj": date.today().strftime("%d/%m/%Y"), "deputes": deputes}
with open('/home/alan/SITE/WEB/scripts/deputes.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=1)
print(f"deputes.json mis à jour : {len(deputes)} députés")
PYEOF
fi

after_stamp=$(stat -c %Y "${JSON}" 2>/dev/null || echo 0)
after_deputes=$(stat -c %Y "${DEPUTES_JSON}" 2>/dev/null || echo 0)

if [[ "${before_stamp}" == "${after_stamp}" && "${before_deputes}" == "${after_deputes}" ]]; then
  echo "[${STAMP}] OK institutions (données inchangées)" >> "${LOG_DIR}/maj.log"
  exit 0
fi

lftp -c "
  open -u skqgfhe-user,Pertuis84120 ftp.cluster100.hosting.ovh.net
  put -O /scripts ${JSON}
  put -O /scripts ${DEPUTES_JSON}
  quit
" >> "${LOG_FILE}" 2>&1 || {
  echo "[${STAMP}] ÉCHEC FTP institutions (voir ${LOG_FILE})" >> "${LOG_DIR}/maj.log"
  exit 1
}

echo "[${STAMP}] OK institutions (mise à jour + upload FTP)" >> "${LOG_DIR}/maj.log"
