"""
fill_template.py — substitute {{TOKENS}} in Proximus Loyalty Movie email templates.

Tokens:
    {{HERO_IMAGE_SRC}}    full URL of hero JPEG (Eloqua CDN or local path)
    {{HERO_IMAGE_ALT}}    alt/title text on hero <img>
    {{H1_INTRO}}          h1 intro line
    {{DATE_TIME_LINE}}    date + time (e.g. "30 avril | 20h00")
    {{BODY_PARAGRAPH}}    main body paragraph (may contain <b> tags)
    {{CTA_HREF}}          full CTA href (base URL + Eloqua query string)
    {{CTA_TEXT}}          CTA button label
    {{VENUE_LIST_HTML}}   <ul>...</ul> rendered from venues array
    {{ABOUT_TITLE}}       movie title in "About" <h2>
    {{SYNOPSIS}}          synopsis paragraph text
    {{CLOSING_LINE}}      closing paragraph before sign-off
    {{LEGAL_DISCLAIMER}}  disclaimer text after <strong>*</strong>
"""
from __future__ import annotations
from typing import Any
import datetime

# Eloqua query-string suffixes — preserved verbatim in output
_ELOQUA_CTA_SUFFIX = {
    "fr": (
        "?l=fr"
        "&u=~~eloqua..type--emailfield..syntax--Loyalty_SFDC1"
        "..innerText--Loyalty_SFDC1..encodeFor--url~~"
        "&elqTrackId=faaf64bd9cea4d95bf6786761ef1446c"
        "&elqTrack=true"
    ),
    "nl": (
        "?l=nl"
        "&u=~~eloqua..type--emailfield..syntax--Loyalty_SFDC1"
        "..innerText--Loyalty_SFDC1..encodeFor--url~~"
        "&elqTrackId=18215f0acfee42538f9e2e7b3d575e97"
        "&elqTrack=true"
    ),
}

_MONTHS_FR = [
    "", "janvier", "février", "mars", "avril", "mai", "juin",
    "juillet", "août", "septembre", "octobre", "novembre", "décembre",
]

_MONTHS_NL = [
    "", "januari", "februari", "maart", "april", "mei", "juni",
    "juli", "augustus", "september", "oktober", "november", "december",
]


def _format_date(iso_date: str, lang: str) -> str:
    """
    Parse an ISO date string (YYYY-MM-DD) and return a language-formatted date.

    FR: "30 avril"
    NL: "30 april"
    """
    if lang not in ("fr", "nl"):
        raise ValueError("lang must be 'fr' or 'nl'")
    dt = datetime.datetime.strptime(iso_date, "%Y-%m-%d")
    if lang == "fr":
        return f"{dt.day} {_MONTHS_FR[dt.month]}"
    return f"{dt.day} {_MONTHS_NL[dt.month]}"


def _format_time(time_str: str, lang: str) -> str:
    """
    Format a HH:MM 24h time string per language.

    FR: "20:00" → "20h00"
    NL: "20:00" → "20.00 uur"
    """
    if lang not in ("fr", "nl"):
        raise ValueError("lang must be 'fr' or 'nl'")
    parts = time_str.split(":")
    if len(parts) != 2 or not parts[0] or not parts[1]:
        raise ValueError(f"time_str must be HH:MM, got {time_str!r}")
    hh, mm = parts
    if lang == "fr":
        return f"{hh}h{mm}"
    return f"{hh}.{mm} uur"


def build_venue_list_html(venues: list[dict], *, lang: str) -> str:
    """Render venue list as an HTML <ul> matching Proximus template style."""
    if lang not in ("fr", "nl"):
        raise ValueError("lang must be 'fr' or 'nl'")

    items = []
    for v in venues:
        name = v[f"name_{lang}"]
        version = v[f"version_{lang}"]
        items.append(
            f'<li><span style="font-size: 14px">'
            f'<strong class="">{name} - </strong>'
            f'{version}.</span></li>'
        )

    return (
        '<ul style="line-height: 1.8; mso-line-height-alt: 25.2px; font-size: 14px;">\n'
        + "\n".join(f"  {item}" for item in items)
        + "\n</ul>"
    )


def fill_template(template_html: str, brief: dict[str, Any], *, lang: str) -> str:
    """Replace all {{TOKEN}} placeholders for the given language."""
    if lang not in ("fr", "nl"):
        raise ValueError("lang must be 'fr' or 'nl'")

    loc = brief[lang]
    movie_title = brief[f"movie_title_{lang}"]
    date_time = f"{_format_date(brief['event_date'], lang)} | {_format_time(brief['event_time'], lang)}"
    cta_href = brief["cta_url"] + _ELOQUA_CTA_SUFFIX[lang]
    about_title = (
        f'À propos de "{movie_title}"' if lang == "fr" else f'Over "{movie_title}"'
    )

    tokens = {
        "{{HERO_IMAGE_SRC}}": loc.get("hero_image_src", ""),
        "{{HERO_IMAGE_ALT}}": movie_title,
        "{{H1_INTRO}}": loc["h1_intro"],
        "{{DATE_TIME_LINE}}": date_time,
        "{{BODY_PARAGRAPH}}": loc["body_paragraph"],
        "{{CTA_HREF}}": cta_href,
        "{{CTA_TEXT}}": loc["cta_text"],
        "{{VENUE_LIST_HTML}}": build_venue_list_html(brief["venues"], lang=lang),
        "{{ABOUT_TITLE}}": about_title,
        "{{SYNOPSIS}}": loc["synopsis"],
        "{{CLOSING_LINE}}": loc["closing_line"],
        "{{LEGAL_DISCLAIMER}}": loc["legal_disclaimer"],
    }

    result = template_html
    for token, value in tokens.items():
        result = result.replace(token, value)
    return result
