"""Digitale PayPal/Stripe-Tools in Jami-Site einbetten."""

from __future__ import annotations

import re
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
TOOL_DIRS = ("bewerbung-pro", "rechnung-pro", "angebot-pro", "briefe-pro")
TOOL_IDS = {
    "bewerbung-pro": "bewerbung",
    "rechnung-pro": "rechnung",
    "angebot-pro": "angebot",
    "briefe-pro": "briefe",
}

STRIPE_BTN = (
    '<button type="button" class="ghost" id="btn-stripe" '
    'data-label="Mit Karte / PayPal bezahlen (Stripe)">'
    "Mit Karte / PayPal (Stripe)</button>"
)
PAY_SCRIPT = '<script src="/js/tools-pay.js" defer></script>'
FUNNEL_SCRIPT = '<script src="/js/tools-funnel.js" defer></script>'


def _inject_stripe(html: str, tool_id: str) -> str:
    if "tools-pay.js" not in html:
        html = html.replace("</body>", f"  {PAY_SCRIPT}\n</body>")
    if 'id="btn-stripe"' not in html:
        if 'id="btn-paypal"' in html:
            html = html.replace('id="btn-paypal"', f'id="btn-paypal"\n          {STRIPE_BTN.strip()}'.replace(
                'id="btn-paypal"\n          <button', 'id="btn-paypal"></button>\n          <button', 1
            ))
            # simpler: insert after btn-paypal closing tag line
            html = re.sub(
                r'(<button[^>]*id="btn-paypal"[^>]*>.*?</button>)',
                r"\1\n          " + STRIPE_BTN,
                html,
                count=1,
                flags=re.S,
            )
        elif 'id="btn-pay"' in html:
            html = re.sub(
                r'(<button[^>]*id="btn-pay"[^>]*>.*?</button>)',
                r"\1\n        " + STRIPE_BTN,
                html,
                count=1,
                flags=re.S,
            )
    if f'data-tool-id="{tool_id}"' not in html and "<body" in html:
        html = re.sub(r"<body([^>]*)>", rf'<body\1 data-tool-id="{tool_id}">', html, count=1)
    return html


def _patch_danke(html: str) -> str:
    if "tools-pay.js" not in html:
        html = html.replace("</body>", f"  {PAY_SCRIPT}\n</body>")
    if "tools-funnel.js" not in html:
        html = html.replace("</body>", f"  {FUNNEL_SCRIPT}\n</body>")
    return html


def _inject_funnel(html: str) -> str:
    if "tools-funnel.js" not in html:
        html = html.replace("</body>", f"  {FUNNEL_SCRIPT}\n</body>")
    return html


def embed_micro_tools(site_root: Path) -> list[Path]:
    site_root = Path(site_root)
    embedded: list[Path] = []

    js_src = ROOT / "tools" / "_shared" / "tools-pay.js"
    funnel_src = ROOT / "tools" / "_shared" / "tools-funnel.js"
    if js_src.is_file() or funnel_src.is_file():
        js_dst = site_root / "js"
        js_dst.mkdir(parents=True, exist_ok=True)
        if js_src.is_file():
            shutil.copy2(js_src, js_dst / "tools-pay.js")
        if funnel_src.is_file():
            shutil.copy2(funnel_src, js_dst / "tools-funnel.js")

    for name in TOOL_DIRS:
        src = ROOT / "tools" / name
        if not src.is_dir():
            continue
        dst_name = name.replace("-pro", "")
        dst = site_root / dst_name
        if dst.exists():
            shutil.rmtree(dst)
        shutil.copytree(src, dst)

        tool_id = TOOL_IDS.get(name, dst_name)
        index = dst / "index.html"
        if index.is_file():
            text = index.read_text(encoding="utf-8")
            text = _inject_stripe(text, tool_id)
            index.write_text(_inject_funnel(text), encoding="utf-8")
        danke = dst / "danke.html"
        if danke.is_file():
            text = danke.read_text(encoding="utf-8")
            danke.write_text(_patch_danke(text), encoding="utf-8")

        embedded.append(dst)
    return embedded
