#!/usr/bin/env python3
"""Publie l'article pilier migration PrestaShop + posts social + IndexNow."""

from __future__ import annotations

import importlib.util
import json
import sys
import urllib.error
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

POST_ID = 15806
FEATURED_MEDIA_ID = 15805
CATEGORY_IDS = [2, 44]  # PrestaShop, E-commerce
TAG_NAMES = [
    "migration prestashop",
    "prestashop 9",
    "prestashop 8",
    "seo e-commerce",
    "redirections 301",
    "google search console",
]

INDEXNOW_KEY = "5f8e4b8b35b143b988c607967725f4b9"
HOST = "www.arnaud-merigeau.fr"
CONTACT_URL = "https://www.arnaud-merigeau.fr/freelance-prestashop/"

SOCIAL_WHO_I_AM = """Je suis Arnaud Mérigeau, freelance PrestaShop & WordPress certifié Experts. Depuis plus de 15 ans, j'accompagne marchands, PME et agences dans le développement de leur e-commerce — migrations, refontes et SEO — grâce à une expertise poussée sur PrestaShop, WordPress et WooCommerce.

Tu prépares une migration 1.7 → 8/9 ou tu veux sécuriser ton référencement avant le go-live ? Discutons-en.

""" + CONTACT_URL

SOCIAL_WHO_I_AM_X = (
    "Je suis Arnaud Mérigeau, freelance certifié Experts (+15 ans). On en parle ? "
    + CONTACT_URL
)

SOCIAL_LINKEDIN = """Tu es encore sur PrestaShop 1.7 ?

La fin de support approche — et une migration mal préparée peut effacer des années de trafic Google en quelques semaines.

J'ai publié un guide complet (checklist 2026) :
→ audit SEO avant migration
→ plan de redirections 301
→ modules, thème, ERP, recette staging
→ monitoring Search Console 30 jours post go-live

Pas de one-click magique : c'est un vrai projet e-commerce + SEO.

Lire le guide : https://www.arnaud-merigeau.fr/migration-prestashop-1-7-vers-9-sans-perdre-seo/

""" + SOCIAL_WHO_I_AM

SOCIAL_X = """PrestaShop 1.7 → 9 : garder ton SEO. Guide 2026 :
https://www.arnaud-merigeau.fr/migration-prestashop-1-7-vers-9-sans-perdre-seo/

""" + SOCIAL_WHO_I_AM_X

SOCIAL_FACEBOOK = """Migration PrestaShop 1.7 vers 8 ou 9 : la question n'est plus « si », mais « comment ne pas perdre son référencement ».

Nouveau guide sur le site — méthode SEO-safe, redirections 301, modules, planning réaliste et FAQ.

Si tu gères une boutique encore en 1.7, ce sera utile avant de signer avec un prestataire.

https://www.arnaud-merigeau.fr/migration-prestashop-1-7-vers-9-sans-perdre-seo/

""" + SOCIAL_WHO_I_AM


def load_draft_module():
    path = ROOT / "scripts" / "create_pillar_migration_prestashop_draft.py"
    spec = importlib.util.spec_from_file_location("migration_draft", path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


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 ping_indexnow(url: str) -> None:
    payload = {
        "host": HOST,
        "key": INDEXNOW_KEY,
        "keyLocation": f"https://{HOST}/{INDEXNOW_KEY}.txt",
        "urlList": [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=30) as resp:
            print(f"IndexNow: HTTP {resp.status}")
    except urllib.error.HTTPError as e:
        print(f"IndexNow: HTTP {e.code}")


def save_social_exports(article_url: str) -> Path:
    out = ROOT / "exports" / "migration-prestashop-2026"
    social = out / "social"
    social.mkdir(parents=True, exist_ok=True)
    posts = {
        "linkedin.txt": SOCIAL_LINKEDIN,
        "x.txt": SOCIAL_X,
        "facebook.txt": SOCIAL_FACEBOOK,
    }
    for name, text in posts.items():
        (social / name).write_text(text.replace("https://www.arnaud-merigeau.fr/migration-prestashop-1-7-vers-9-sans-perdre-seo/", article_url) + "\n", encoding="utf-8")
    readme = out / "README.txt"
    readme.write_text(
        f"Article publié : {article_url}\n\n"
        "Posts prêts à coller :\n"
        "- social/linkedin.txt\n"
        "- social/x.txt\n"
        "- social/facebook.txt\n",
        encoding="utf-8",
    )
    return out


def main() -> int:
    draft = load_draft_module()
    cfg = load_config()
    base = cfg.wp_base_url.rstrip("/")

    tag_ids = [get_or_create_tag(base, cfg.wp_user, cfg.wp_application_password, t) for t in TAG_NAMES]

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

    url = f"{base}/wp-json/wp/v2/posts/{POST_ID}"
    _, post = wp_client._request(
        "POST",
        url,
        cfg.wp_user,
        cfg.wp_application_password,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )

    article_url = post.get("link", f"{base}/{draft.SLUG}/")
    print(f"Publié — ID {post.get('id')} — {article_url}")

    out_dir = save_social_exports(article_url)
    print(f"Posts social : {out_dir / 'social'}/")

    ping_indexnow(article_url)
    return 0


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