#!/usr/bin/env python3
"""Article pilier « PrestaShop ou Shopify » + kit social — cible SEO prestashop shopify."""

from __future__ import annotations

import json
import subprocess
import sys
import urllib.parse
import urllib.request
from pathlib import Path

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

from article_studio.config import load_config  # noqa: E402
from article_studio import wp_client  # noqa: E402
from prestashop_shopify_content import build_content  # noqa: E402

BASE = "https://www.arnaud-merigeau.fr"
PS = f"{BASE}/freelance-prestashop/"
PS9 = f"{BASE}/prestashop-9/"
MIGRATION = f"{BASE}/migration-prestashop-1-7-vers-9-sans-perdre-seo/"
EXPORT = f"{BASE}/produit/module-export-comptable-pour-prestashop/"
CONTACT = f"{BASE}/contact/"

TITLE = "PrestaShop ou Shopify en 2026 : pourquoi PrestaShop reste le choix rationnel des PME françaises"
SLUG = "prestashop-shopify-comparatif-migration-2026"
YOAST_TITLE = "PrestaShop Shopify : comparatif 2026 - pourquoi choisir PrestaShop"
YOAST_DESC = (
    "PrestaShop ou Shopify en 2026 ? Comparatif exhaustif pour PME françaises : TCO réel, "
    "conformité TVA, SEO, B2B, facturation électronique ; et pourquoi PrestaShop gagne sur le moyen terme."
)
FOCUS = "prestashop shopify"
EXCERPT = (
    "PrestaShop ou Shopify ? Après 15 ans sur PrestaShop et des centaines de projets, voici le comparatif "
    "le plus complet du web francophone, avec un verdict clair pour les PME qui veulent maîtriser leurs coûts, "
    "leur SEO et leur comptabilité."
)
POST_ID = 16111
FEATURED_ID = 16110

IMG_FEATURED_LOCAL = ROOT / "assets" / "prestashop-shopify-comparatif-2026-featured.png"
IMG_TCO_LOCAL = ROOT / "assets" / "prestashop-shopify-tco-2026.png"
IMG_SCORE_LOCAL = ROOT / "assets" / "prestashop-shopify-score-2026.png"
KIT_DIR = ROOT / "www/propositions/kit-social-prestashop-shopify-2026"
CAMPAIGN = "prestashop-shopify-2026"

CATEGORY_IDS = [2]  # PrestaShop
TAG_NAMES = ["PrestaShop", "Shopify", "E-commerce", "Migration", "SEO"]


def build_social_posts(article_url: str) -> dict:
    utm_li = f"{article_url}?utm_source=linkedin&utm_medium=social&utm_campaign={CAMPAIGN}&utm_content=linkedin"
    utm_x = f"{article_url}?utm_source=twitter&utm_medium=social&utm_campaign={CAMPAIGN}&utm_content=x"
    utm_fb = f"{article_url}?utm_source=facebook&utm_medium=social&utm_campaign={CAMPAIGN}&utm_content=facebook"
    utm_cta_li = f"{CONTACT}?utm_source=linkedin&utm_medium=social&utm_campaign={CAMPAIGN}&utm_content=linkedin-cta"
    utm_cta_fb = f"{CONTACT}?utm_source=facebook&utm_medium=social&utm_campaign={CAMPAIGN}&utm_content=facebook-cta"

    linkedin = f"""PrestaShop ou Shopify en 2026 ?

Spoiler : pour une PME française avec du CA, ce n'est pas 50/50.

J'ai passé au crible les comparatifs du web (Nugg.ad, Neocell, Transacts, UpWedo…) et confronté avec 15 ans de terrain PrestaShop :

→ TCO 3 ans : ~8 800 € PS vs ~19 350 € Shopify (150 k€ CA/an)
→ 0 % commission plateforme sur PrestaShop
→ B2B, multiboutique, SEO, compta FR : PrestaShop gagne

Shopify = OK pour un test D2C sans contrainte. Pour le reste : PrestaShop 9.

Comparatif exhaustif (17 sections) 👇
{utm_li}

👋 Arnaud Mérigeau · freelance PrestaShop certifié Experts (+15 ans)
Migration Shopify → PrestaShop, PS 9, TMA.

Tu paies combien d'apps Shopify par mois ?
→ Audit : {utm_cta_li}

#PrestaShop #Shopify #Ecommerce #Migration #SEO"""

    x = f"""PrestaShop vs Shopify 2026 — verdict PME FR :

PS gagne sur TCO, SEO, B2B, 0 % commission.

Comparatif exhaustif (17 sections) 👇
{utm_x}

👋 Freelance certifié Experts · {CONTACT.replace('https://', '')}"""

    facebook = f"""PrestaShop ou Shopify en 2026 ?

Pour une PME française, ce n'est pas un coin flip.

J'ai publié le comparatif le plus complet du web francophone :
• TCO 3 ans chiffré (PS ~8 800 € vs Shopify ~19 350 €)
• Frais de transaction Shopify (le piège)
• Conformité FR, facturation électronique
• SEO, B2B, catalogue, multiboutique
• Pourquoi migrer vers Shopify coûte souvent plus cher

Verdict : PrestaShop 9 pour construire un actif durable.

👉 Lire l'article :
{utm_fb}

👋 Arnaud Mérigeau · freelance PrestaShop certifié Experts (+15 ans)
→ Me contacter : {utm_cta_fb}

#PrestaShop #Shopify #Ecommerce"""

    return {
        "meta": {
            "title": "Kit social — PrestaShop vs Shopify 2026",
            "slug": "kit-social-prestashop-shopify-2026",
            "status": "ready",
            "period": "Publication à planifier",
            "cadence": "1 post — article pilier SEO",
            "utm_campaign": CAMPAIGN,
            "description": "Promotion de l'article comparatif PrestaShop / Shopify — cible requête prestashop shopify.",
            "contact_url": CONTACT,
        },
        "footer": {
            "linkedin": (
                "👋 Je suis Arnaud Mérigeau, freelance PrestaShop & WordPress certifié Experts (+15 ans). "
                "Migration, TMA, modules métier.\n→ Me contacter : " + CONTACT
            ),
            "x": f"👋 Freelance certifié Experts · PrestaShop / WP · {CONTACT.replace('https://', '')}",
            "facebook": (
                "👋 Arnaud Mérigeau · freelance PrestaShop certifié Experts (+15 ans)\n→ Me contacter : "
                + CONTACT
            ),
        },
        "posts": [
            {
                "id": "prestashop-shopify-2026",
                "date": "2026-08-20",
                "day": "À publier",
                "time": "10h00",
                "type": "Article / SEO",
                "title": TITLE,
                "url": article_url,
                "url_slug": SLUG,
                "hashtags": ["#PrestaShop", "#Shopify", "#Ecommerce", "#Migration", "#SEO"],
                "objective": "Positionner sur prestashop shopify + trafic vers article et contact",
                "note": "Visuel 1920×1080 JPG. Article publié. Un visuel pour LinkedIn, X et Facebook.",
                "category": "E-commerce",
                "resource_label": "Lire le comparatif",
                "linkedin": linkedin,
                "x": x,
                "facebook": facebook,
                "visual": {
                    "file": "visuels/visuel-prestashop-shopify-2026.jpg",
                    "alt": "PrestaShop ou Shopify ? — comparatif 2026 arnaud-merigeau.fr",
                    "format": "1920×1080 JPG 16:9 — LinkedIn, X et Facebook",
                },
            }
        ],
    }


def get_or_create_tag(base: str, user: str, password: str, name: str) -> int:
    slug = name.lower().replace(" ", "-")
    lookup = f"{base}/wp-json/wp/v2/tags?slug={urllib.parse.quote(slug)}"
    _, tags = wp_client._request("GET", lookup, user, password)
    if tags:
        return int(tags[0]["id"])
    _, tag = wp_client._request(
        "POST",
        f"{base}/wp-json/wp/v2/tags",
        user,
        password,
        data=json.dumps({"name": name, "slug": slug}).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    return int(tag["id"])


def copy_featured_to_assets() -> Path | None:
    visual_png = KIT_DIR / "visuels" / "visuel-prestashop-shopify-2026.png"
    if visual_png.is_file():
        IMG_FEATURED_LOCAL.parent.mkdir(parents=True, exist_ok=True)
        IMG_FEATURED_LOCAL.write_bytes(visual_png.read_bytes())
        return IMG_FEATURED_LOCAL
    return None


def get_media_url(base: str, user: str, password: str, media_id: int) -> str:
    _, media = wp_client._request(
        "GET",
        f"{base}/wp-json/wp/v2/media/{media_id}",
        user,
        password,
    )
    return media.get("source_url") or media.get("guid", {}).get("rendered", "")


def upload_image(
    base: str,
    user: str,
    password: str,
    path: Path,
    *,
    alt: str,
    title: str,
) -> str:
    if not path.is_file():
        raise FileNotFoundError(f"Image introuvable : {path}")
    print(f"Upload : {path.name}")
    media = wp_client.upload_media(base, user, password, path, alt_text=alt, title=title)
    url = media.get("source_url") or media.get("guid", {}).get("rendered", "")
    print(f"  media id={media.get('id')} — {url}")
    return url


def build_article_content(
    *,
    img_hero: str,
    img_score: str,
    img_tco: str,
) -> str:
    return build_content(
        ps=PS,
        ps9=PS9,
        migration=MIGRATION,
        export=EXPORT,
        contact=CONTACT,
        img_hero=img_hero,
        img_score=img_score,
        img_tco=img_tco,
    )


def save_exports(article_url: str, post_id: int | None, content: str) -> None:
    out = ROOT / "exports" / "prestashop-shopify-2026"
    out.mkdir(parents=True, exist_ok=True)
    (out / "content.html").write_text(content.strip() + "\n", encoding="utf-8")
    (out / "seo.yaml").write_text(
        "\n".join(
            [
                f"titre_seo: {YOAST_TITLE}",
                f"slug: {SLUG}",
                f"meta_description: {YOAST_DESC}",
                f"focus_keyword: {FOCUS}",
                f"url: {article_url}",
                f"post_id: {post_id or 'n/a'}",
                "",
            ]
        ),
        encoding="utf-8",
    )
    kit_data = build_social_posts(article_url)
    KIT_DIR.mkdir(parents=True, exist_ok=True)
    (KIT_DIR / "posts.json").write_text(
        json.dumps(kit_data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    print(f"Kit social : {KIT_DIR / 'posts.json'}")


def ping_indexnow(article_url: str) -> None:
    key = "5f8e4b8b35b143b988c607967725f4b9"
    payload = {
        "host": "www.arnaud-merigeau.fr",
        "key": key,
        "keyLocation": f"https://www.arnaud-merigeau.fr/{key}.txt",
        "urlList": [article_url],
    }
    req = urllib.request.Request(
        "https://api.indexnow.org/indexnow",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json; charset=utf-8"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=20) as resp:
            print(f"IndexNow {resp.status} — {article_url}")
    except Exception as exc:  # noqa: BLE001
        print(f"IndexNow ignoré : {exc}")


def main() -> int:
    print("Génération visuel social…")
    visual_py = str(ROOT / "scripts/generate_prestashop_shopify_social_visual.py")
    article_visuals_py = str(ROOT / "scripts/generate_prestashop_shopify_article_visuals.py")
    for py in ("/usr/bin/python3", sys.executable):
        try:
            subprocess.run([py, visual_py], check=True)
            subprocess.run([py, article_visuals_py], check=True)
            break
        except (subprocess.CalledProcessError, FileNotFoundError):
            continue
    else:
        raise RuntimeError("Impossible de générer les visuels (Pillow requis).")
    copy_featured_to_assets()

    cfg = load_config()
    if not cfg.wp_user or not cfg.wp_application_password:
        print("Credentials WP manquants — exports locaux uniquement.")
        article_url = f"{BASE}/{SLUG}/"
        content = build_article_content(
            img_hero="/assets/prestashop-shopify-comparatif-2026-featured.png",
            img_score="/assets/prestashop-shopify-score-2026.png",
            img_tco="/assets/prestashop-shopify-tco-2026.png",
        )
        save_exports(article_url, None, content)
        subprocess.run(
            [sys.executable, str(ROOT / "scripts/generate-social-kit-page.py"), str(KIT_DIR)],
            check=False,
        )
        return 0

    base = cfg.wp_base_url.rstrip("/")
    user = cfg.wp_user
    password = cfg.wp_application_password
    featured_id = FEATURED_ID

    print("Images article…")
    img_hero = get_media_url(base, user, password, featured_id)
    img_score = upload_image(
        base,
        user,
        password,
        IMG_SCORE_LOCAL,
        alt="Score comparatif PrestaShop vs Shopify : 12 critères pour PrestaShop, 3 pour Shopify",
        title="Score comparatif PrestaShop vs Shopify 2026",
    )
    img_tco = upload_image(
        base,
        user,
        password,
        IMG_TCO_LOCAL,
        alt="Graphique TCO 3 ans PrestaShop vs Shopify : 8 800 € contre 19 350 €",
        title="TCO 3 ans PrestaShop vs Shopify 2026",
    )
    content = build_article_content(img_hero=img_hero, img_score=img_score, img_tco=img_tco)

    print("Tags…")
    tag_ids = [get_or_create_tag(base, user, password, t) for t in TAG_NAMES]

    payload: dict = {
        "title": TITLE,
        "content": content.strip(),
        "excerpt": EXCERPT,
        "status": "publish",
        "slug": SLUG,
        "author": cfg.wp_author_id,
        "categories": CATEGORY_IDS,
        "tags": tag_ids,
        "featured_media": featured_id,
        "meta": {
            "_yoast_wpseo_title": YOAST_TITLE,
            "_yoast_wpseo_metadesc": YOAST_DESC,
            "_yoast_wpseo_focuskw": FOCUS,
            "_yoast_wpseo_linkdex": "78",
        },
    }

    print(f"Mise à jour WordPress post {POST_ID}…")
    _, post = wp_client._request(
        "POST",
        f"{base}/wp-json/wp/v2/posts/{POST_ID}",
        user,
        password,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )

    post_id = post.get("id")
    link = post.get("link") or f"{BASE}/{SLUG}/"
    print(f"Mis à jour — ID {post_id}")
    print(f"Lien : {link}")

    save_exports(link, post_id, content)
    subprocess.run(
        [sys.executable, str(ROOT / "scripts/generate-social-kit-page.py"), str(KIT_DIR)],
        check=True,
    )
    ping_indexnow(link)
    return 0


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