#!/usr/bin/env python3
"""Ajoute du maillage interne vers le module Pennylane sur les articles publiés."""

from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))

from article_studio.config import load_config
from article_studio.wp_client import _request

BASE = "https://www.arnaud-merigeau.fr"
PROD_PENNYLANE = f"{BASE}/produit/module-prestashop-synchronisation-pennylane/"
PENNYLANE_GUIDE = f"{BASE}/prestashop-pennylane-synchronisation-facture-electronique-2026/"
FE_GUIDE = f"{BASE}/facturation-electronique-prestashop-wordpress-2026/"

# Articles à enrichir : id → liste de (needle, insert_after_needle, block)
PATCHES: dict[int, list[tuple[str, str]]] = {
    15863: [
        (
            "Mon conseil terrain en 2026 pour une boutique PrestaShop PME / ETI : vise un <strong>CSV propre et stable</strong>",
            (
                '<h3 id="pennylane-prestashop">11 bis. Pennylane : synchronisation API en temps réel</h3>\n'
                f'<p>Si ton cabinet ou ta structure est passée sur <strong>Pennylane</strong>, l\'export CSV mensuel ne suffit pas toujours : tu as aussi besoin que chaque vente web remonte <strong>client + facture</strong> dans Pennylane sans ressaisie — surtout à l\'approche de la <a href="{FE_GUIDE}">facture électronique</a> (réception obligatoire le 1<sup>er</sup> septembre 2026).</p>\n'
                f'<p>J\'ai développé un <a href="{PROD_PENNYLANE}"><strong>module PrestaShop synchronisation Pennylane</strong></a> (API v2, déclenchement par statut commande, facture brouillon ou import PDF, multiboutique, journal intégré). Guide dédié : <a href="{PENNYLANE_GUIDE}">PrestaShop + Pennylane avant la facture électronique</a>. Les deux modules se complètent : Pennylane en temps réel, export CSV pour le cabinet si besoin.</p>\n'
            ),
        ),
    ],
    15961: [
        (
            "Guide détaillé : <a href=\"https://www.arnaud-merigeau.fr/export-comptable-prestashop-2026-formats-erreurs-module-csv/\">export comptable PrestaShop 2026</a>.",
            (
                f'<p>Tu es sur <strong>Pennylane</strong> ? Ajoute le <a href="{PROD_PENNYLANE}">module synchronisation Pennylane</a> : à chaque statut commande configuré, client et facture sont créés dans Pennylane via API (compatible PS 1.7.8 à 9.1). Calendrier facture électronique et config pas à pas : <a href="{PENNYLANE_GUIDE}">guide PrestaShop Pennylane 2026</a>.</p>\n'
            ),
        ),
    ],
    15329: [
        (
            '[btn type="noir" url="https://prestashop.pxf.io/xJ2VM1" ancre="Voir le Connecteur Pennylane - PrestaShop" target="_blank"]',
            (
                f'<p><strong>Alternative — module Latoutfrancais :</strong> si tu préfères un connecteur maintenu par le même éditeur que l\'<a href="{BASE}/produit/module-export-comptable-pour-prestashop/">export comptable CSV PrestaShop</a>, le <a href="{PROD_PENNYLANE}"><strong>module synchronisation Pennylane</strong></a> pousse clients et factures vers Pennylane via API v2 à chaque changement de statut commande (journal, renvoi manuel, multiboutique, PS 1.7.8 à 9.1). Guide opérationnel : <a href="{PENNYLANE_GUIDE}">PrestaShop + Pennylane et facture électronique</a>.</p>\n\n&nbsp;\n\n'
            ),
        ),
    ],
}


def patch_content(content: str, needle: str, block: str) -> tuple[str, bool]:
    if block.strip() in content:
        return content, False
    idx = content.find(needle)
    if idx < 0:
        return content, False
    # insert block before needle for export comptable (section before conseil)
    if "11 bis. Pennylane" in block:
        return content[:idx] + block + content[idx:], True
    # insert after needle for others
    end = idx + len(needle)
    return content[:end] + "\n" + block + content[end:], True


def main() -> int:
    cfg = load_config()
    base = cfg.wp_base_url.rstrip("/")
    user = cfg.wp_user
    pwd = cfg.wp_application_password.replace(" ", "")

    for post_id, rules in PATCHES.items():
        _, post = _request(
            "GET",
            f"{base}/wp-json/wp/v2/posts/{post_id}?context=edit",
            user,
            pwd,
        )
        content = post["content"]["raw"]
        title = post["title"]["raw"] if "raw" in post["title"] else post["title"]["rendered"]
        changed = False

        for needle, block in rules:
            content, ok = patch_content(content, needle, block)
            if ok:
                changed = True
                print(f"  patch OK on post {post_id}")
            else:
                if block.strip() in content:
                    print(f"  déjà présent — post {post_id}")
                else:
                    print(f"  ATTENTION: needle introuvable — post {post_id}")
                    print(f"    needle: {needle[:80]}…")

        if not changed:
            continue

        _, updated = _request(
            "POST",
            f"{base}/wp-json/wp/v2/posts/{post_id}",
            user,
            pwd,
            data=json.dumps({"content": content}).encode("utf-8"),
            headers={"Content-Type": "application/json"},
        )
        print(f"Mis à jour : {post_id} — {title}")
        print(f"  → {updated.get('link')}")

    print("\nTerminé.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
