"""Jami – Custom Domain & siteUrl (Cloudflare Pages, Stripe, Rechtstexte)."""

from __future__ import annotations

import json
import os
import re
from pathlib import Path

PAGES_PROJECT = "jami"
PAGES_DEV_HOST = "jami-9g3.pages.dev"
PAGES_DEV_URL = f"https://{PAGES_DEV_HOST}"

REPO_ROOT = Path(__file__).resolve().parents[1]
SECRETS_FILE = REPO_ROOT / "data" / "jami-secrets.local.json"

_DOMAIN_RE = re.compile(
    r"^(?:https?://)?([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*)$",
    re.I,
)


def normalize_site_url(raw: str) -> str:
    s = (raw or "").strip().rstrip("/")
    if not s:
        return PAGES_DEV_URL
    if s.startswith("http://") or s.startswith("https://"):
        return s.rstrip("/")
    return f"https://{s}"


def normalize_domain(raw: str) -> str:
    url = normalize_site_url(raw)
    host = url.split("://", 1)[-1].split("/", 1)[0].lower()
    m = _DOMAIN_RE.match(host)
    if not m:
        raise ValueError(f"Ungültige Domain: {raw!r}")
    return m.group(1)


def load_secrets() -> dict:
    if not SECRETS_FILE.is_file():
        return {}
    try:
        return json.loads(SECRETS_FILE.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return {}


def save_secrets(data: dict) -> None:
    SECRETS_FILE.parent.mkdir(parents=True, exist_ok=True)
    SECRETS_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


def resolve_site_url(*, env: os._Environ[str] | None = None) -> str:
    """Priorität: JAMI_SITE_URL → jami-secrets.local.json → pages.dev."""
    e = env if env is not None else os.environ
    from_env = (e.get("JAMI_SITE_URL") or "").strip()
    if from_env:
        return normalize_site_url(from_env)

    s = load_secrets()
    for key in ("jami_site_url", "site_url", "custom_domain", "domain"):
        val = str(s.get(key, "")).strip()
        if val and "HIER" not in val.upper() and "DEINE" not in val.upper():
            return normalize_site_url(val)
    return PAGES_DEV_URL


def stripe_webhook_url(site_url: str | None = None) -> str:
    return f"{(site_url or resolve_site_url()).rstrip('/')}/api/stripe-webhook"


def domain_setup_guide(*, domain: str, site_url: str | None = None) -> str:
    host = normalize_domain(domain)
    url = normalize_site_url(site_url or host)
    is_sub = host.count(".") >= 2
    sub_label = host.split(".", 1)[0] if is_sub else "@"

    dns_block = ""
    if is_sub:
        dns_block = f"""
DNS (Domain bei Cloudflare):
  Typ: CNAME
  Name: {sub_label}
  Ziel: {PAGES_DEV_HOST}
  Proxy: AN (orange Wolke)
"""
    else:
        dns_block = f"""
DNS (Root-Domain, z. B. jami.de):
  Cloudflare Pages schlägt meist vor:
  • CNAME @ → {PAGES_DEV_HOST}  (wenn Registrar es erlaubt)
  • oder A/AAAA auf die IPs aus dem Pages-Dialog
  • oft zusätzlich www → {PAGES_DEV_HOST}
"""

    return f"""JAMI – EIGENE DOMAIN EINRICHTEN
==============================

Ziel: {url}
Pages-Projekt: {PAGES_PROJECT} ({PAGES_DEV_URL})

SCHRITT 1 – Cloudflare Pages
----------------------------
1. https://dash.cloudflare.com → Workers & Pages → {PAGES_PROJECT}
2. Custom domains → Set up a custom domain
3. Domain eingeben: {host}
4. DNS-Hinweise von Cloudflare übernehmen (siehe unten)

SCHRITT 2 – DNS
---------------{dns_block}

SCHRITT 3 – Jami neu bauen & deployen
-------------------------------------
  python scripts/setup_jami_domain.py {host} --deploy

  (Setzt JAMI_SITE_URL, Datenschutz-URL, Stripe-Webhook)

SCHRITT 4 – Prüfen
------------------
  {url}/impressum
  {url}/api/health
  Shop → Stripe-Testkauf (4242…)

Hinweise
--------
• pages.dev bleibt als Backup erreichbar.
• SSL-Zertifikat: Cloudflare stellt es automatisch aus (meist 5–15 Min.).
• Stripe-Webhook: {stripe_webhook_url(url)}
• Bei E-Mail/Push: MAIL_FROM und VAPID_SUBJECT an {host} anpassen.

Empfohlene Domain:
  jami-dating.de
"""


def write_domain_guide(site_root: Path, *, domain: str | None = None) -> Path:
    site_root.mkdir(parents=True, exist_ok=True)
    d = domain or normalize_domain(resolve_site_url())
    if d == PAGES_DEV_HOST:
        body = domain_setup_guide(domain="jami.ki-web-studio.de")
        body = (
            f"Aktuell: {PAGES_DEV_URL}\n\n"
            "Eigene Domain noch nicht gesetzt.\n"
            "Empfehlung: jami-dating.de\n\n"
            + body
        )
    else:
        body = domain_setup_guide(domain=d)
    path = site_root / "DOMAIN_EINRICHTEN.txt"
    path.write_text(body, encoding="utf-8")
    return path
