from __future__ import annotations

from pathlib import Path

FORMAT_INSTRUCTION = """
FORMAT DE SORTIE (strict — respecte l’ordre et les balises) :

1) Bloc ```yaml``` avec :
   titre_seo, slug, meta_description, focus_keyword, categorie_wp, tags
   + 2 variantes : variante_titre_seo_2, variante_meta_2 (et optionnel _3)

2) Bloc ```json``` minifié UTF-8 avec :
   "title" (H1 WordPress), "excerpt" (texte brut), "image_prompt" (prompt DALL-E
   détaillé, style professionnel blog tech e-commerce, sans texte dans l’image),
   "image_alt" (alt SEO de l’image à la une)

3) Bloc ```html``` : corps complet prêt WordPress (intro, <!--more-->, sommaire,
   h2/h3, tableaux, FAQ, conclusion). Pas de H1 dans le HTML.

4) Bloc ```social``` avec 3 sous-sections exactes :
   ## LinkedIn
   (post putaclic, valeur métier + expertise, lien article en fin, SANS emoji)
   ## X
   (accroche percutante + lien, max ~280 caractères utiles, SANS emoji)
   ## Facebook
   (ton entraide communauté marchands + lien, SANS emoji)

Remplace dans les posts sociaux le placeholder {{ARTICLE_URL}} par l’URL finale :
{article_url}

Aucun texte avant le premier ```yaml```. Aucun texte après le bloc social.
"""


def load_master_prompt(path: Path) -> str:
    if not path.is_file():
        raise FileNotFoundError(f"Prompt maître introuvable : {path}")
    return path.read_text(encoding="utf-8")


def build_user_prompt(
    *,
    sujet: str,
    article_url: str,
    source: dict[str, str] | None = None,
    keywords: str | None = None,
    internal_links: str | None = None,
    status: str = "draft",
) -> str:
    parts = [
        FORMAT_INSTRUCTION.format(article_url=article_url),
        f'\nStatut WordPress visé : "{status}".',
        "\n--- SUJET / ANGLE ---",
        sujet.strip(),
    ]

    if keywords:
        parts.extend(["\nMots-clés secondaires :", keywords.strip()])

    if internal_links:
        parts.extend(["\nLiens internes à citer si pertinent :", internal_links.strip()])

    if source:
        parts.extend(
            [
                "\n--- SOURCE WEB (inspiration — ne pas copier, reformuler avec ton expertise) ---",
                f"URL : {source.get('url', '')}",
                f"Titre source : {source.get('title', '')}",
                f"Description : {source.get('description', '')}",
                f"Extrait :\n{source.get('text', '')}",
            ]
        )

    parts.append(
        "\nRappel : article long-form 3000–5000 mots, tutoiement, sans emoji, "
        "putaclic honnête (CTR sans surpromesse)."
    )
    return "\n".join(parts)
