#!/usr/bin/env bash
# Prélude du replay PROD — reproduit les étapes hors-manifeste répétées avec
# succès sur la sandbox le 2026-07-11 (fiches, lignes, refs/dates, validations).
# À exécuter PAR L'HUMAIN, clé prod en main, AVANT les deux promote apply :
#
#   export DOLIBARR_PROD_WRITE_KEY=...   # jamais stockée
#   export ARCO_PROMOTE_CONFIRM=I-UNDERSTAND-THIS-WRITES-PROD
#   bash prod-replay-prelude.sh
#   bin/arcodange promote apply manifest-A-km-payments.json --target prod
#   bin/arcodange promote apply manifest-B-suppliers.json   --target prod
#
# Chaque étape relit l'objet après écriture. S'arrête au premier écart.
set -euo pipefail

ERP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Adapter si le script n'est pas copié dans le repo erp :
DPW="${DPW:-$HOME/Work/Arcodange/erp/.claude/skills/dolibarr-sandbox-write/scripts/dol-prod-write.sh}"
[ -x "$DPW" ] || { echo "dol-prod-write.sh introuvable ($DPW)"; exit 1; }

jqv() { jq -r "$1" ; }
step() { echo; echo "=== $* ==="; }

step "0. Pré-vols : les 7 pièces prod dans l'état attendu"
for i in 14 15 16 17; do "$DPW" GET "/invoices/$i" | jq -e '(.statut=="0")' >/dev/null \
  || { echo "invoice $i n'est pas en brouillon — STOP (état prod ≠ répétition)"; exit 1; }; done
for i in 12 14 15; do "$DPW" GET "/supplierinvoices/$i" | jq -e '(.statut=="0")' >/dev/null \
  || { echo "supplierinvoice $i n'est pas en brouillon — STOP"; exit 1; }; done
echo "OK — 7 brouillons présents"

step "1. Fiches fournisseur : Anthropic (11) + Mistral (12)"
"$DPW" PUT /thirdparties/11 '{"fournisseur":1,"code_fournisseur":"-1"}' >/dev/null
"$DPW" PUT /thirdparties/12 '{"fournisseur":1,"code_fournisseur":"-1"}' >/dev/null
for i in 11 12; do "$DPW" GET "/thirdparties/$i" | jq -r '[.id,.name,.fournisseur,.code_fournisseur]|@tsv'; done

step "2. Brouillons fournisseurs : refs, dates, lignes manquantes, paye fantôme"
EP_ANT=$(python3 -c "import datetime;print(int(datetime.datetime(2026,4,12).timestamp()))")
EP_MIS=$(python3 -c "import datetime;print(int(datetime.datetime(2026,4,2).timestamp()))")
"$DPW" PUT /supplierinvoices/12 '{"ref_supplier":"F1046"}' >/dev/null
"$DPW" PUT /supplierinvoices/14 "{\"ref_supplier\":\"9BF0758D-695749\",\"date\":${EP_ANT}}" >/dev/null
"$DPW" PUT /supplierinvoices/15 "{\"ref_supplier\":\"MSTRL-API-814045-001\",\"date\":${EP_MIS}}" >/dev/null
# lignes absentes sur 12 et 14 (constaté identique en sandbox ; re-vérifié ici)
L12=$("$DPW" GET /supplierinvoices/12 | jq '.lines|length')
L14=$("$DPW" GET /supplierinvoices/14 | jq '.lines|length')
[ "$L12" = "0" ] && "$DPW" POST /supplierinvoices/12/lines '{"description":"Apport d affaire Arcodange - Projet — juin 2026 (Hiway F1046)","pu_ht":"219.50","qty":"1","tva_tx":"20","product_type":"1"}' >/dev/null
[ "$L14" = "0" ] && "$DPW" POST /supplierinvoices/14/lines '{"description":"Claude Pro — abonnement avril 2026 (facture 9BF0758D-695749, autoliquidation UE)","pu_ht":"180.00","qty":"1","tva_tx":"0","product_type":"1"}' >/dev/null
"$DPW" PUT /supplierinvoices/14 '{"paye":0}' >/dev/null
"$DPW" PUT /supplierinvoices/15 '{"paye":0}' >/dev/null
for i in 12 14 15; do "$DPW" GET "/supplierinvoices/$i" | jq -r '[.id,.ref_supplier,(.lines|length),.total_ttc,.paye]|@tsv'; done
# garde-fou totaux (l'ajout de ligne ne doit PAS doubler)
"$DPW" GET /supplierinvoices/12 | jq -e '.total_ttc=="263.40000000"' >/dev/null || { echo "total 12 inattendu — STOP"; exit 1; }
"$DPW" GET /supplierinvoices/14 | jq -e '.total_ttc=="180.00000000"' >/dev/null || { echo "total 14 inattendu — STOP"; exit 1; }

step "3. Validation clients — ordre chronologique (mai avant juin)"
for i in 14 15 16 17; do "$DPW" POST "/invoices/$i/validate" '{"idwarehouse":0,"notrigger":0}' >/dev/null; done
for i in 14 15 16 17; do "$DPW" GET "/invoices/$i" | jq -r '[.id,.ref,.statut,.total_ttc]|@tsv'; done

step "4. Validation fournisseurs"
for i in 12 14 15; do "$DPW" POST "/supplierinvoices/$i/validate" '{"idwarehouse":0,"notrigger":0}' >/dev/null; done
for i in 12 14 15; do "$DPW" GET "/supplierinvoices/$i" | jq -r '[.id,.ref,.ref_supplier,.statut]|@tsv'; done

echo
echo "Prélude OK — enchaîner :"
echo "  bin/arcodange promote apply manifest-A-km-payments.json --target prod"
echo "  bin/arcodange promote apply manifest-B-suppliers.json   --target prod"
