"""VidPuls / JamPulse – Zahlungsoptionen (Stripe, PayPal, SEPA)."""

from __future__ import annotations

import json
from pathlib import Path
from urllib.parse import quote

from jam.jampulse_brand import PRODUCT_BRAND
from jam.paypal_donate import PAYPAL_EMAIL

ROOT = Path(__file__).resolve().parents[1]
CONFIG_NAMES = ("vidpuls-config.json", "clipwelle-config.json", "jampulse-config.json")

# Stripe Checkout – absteigend (wie cloudflare/functions/_lib/stripe.js)
STRIPE_CHECKOUT_PRESETS: list[list[str]] = [
    ["card", "link", "paypal", "klarna", "amazon_pay", "sepa_debit"],
    ["card", "link", "paypal", "klarna", "amazon_pay"],
    ["card", "link", "paypal", "klarna"],
    ["card", "link", "paypal"],
    ["card", "link"],
    ["card"],
]

PAYMENT_LABELS = {
    "card": "Kredit-/Debitkarte",
    "link": "Link · Apple Pay · Google Pay",
    "paypal": "PayPal",
    "klarna": "Klarna · Später zahlen",
    "amazon_pay": "Amazon Pay",
    "sepa_debit": "SEPA-Lastschrift",
}


def _config() -> dict:
    for name in CONFIG_NAMES:
        cfg = ROOT / "data" / name
        if cfg.is_file():
            try:
                return json.loads(cfg.read_text(encoding="utf-8"))
            except (json.JSONDecodeError, OSError):
                pass
    return {}


def paypal_email() -> str:
    return str(_config().get("paypal_email") or PAYPAL_EMAIL).strip()


def paypal_product_url(
    *,
    product_id: str,
    price_eur: float,
    title: str,
    return_url: str = "",
) -> str:
    """Direkt-PayPal ohne Stripe (Fallback). Optional mit Rückkehr-URL."""
    business = quote(paypal_email())
    amount = f"{price_eur:.2f}"
    item = quote(f"{PRODUCT_BRAND} – {title}")
    custom = quote(product_id)
    url = (
        f"https://www.paypal.com/cgi-bin/webscr?"
        f"cmd=_xclick&business={business}"
        f"&currency_code=EUR&amount={amount}"
        f"&item_name={item}&custom={custom}"
        f"&no_shipping=1&charset=utf-8"
    )
    if return_url.strip():
        url += f"&return={quote(return_url.strip())}&rm=2"
    return url


def sepa_info() -> dict | None:
    bank = _config().get("bank_transfer") or {}
    iban = str(bank.get("iban") or "").replace(" ", "").strip()
    if not iban:
        return None
    return {
        "holder": str(bank.get("holder") or "David Prechtel"),
        "iban": iban,
        "bic": str(bank.get("bic") or "").strip(),
        "bank": str(bank.get("bank") or "").strip(),
        "note": f"Verwendungszweck: {PRODUCT_BRAND} + deine E-Mail. Freischaltung innerhalb 24 h.",
    }


def payment_methods_summary() -> list[str]:
    """Kundenfreundliche Liste aller akzeptierten Methoden."""
    return [
        PAYMENT_LABELS["card"],
        PAYMENT_LABELS["link"],
        PAYMENT_LABELS["paypal"],
        PAYMENT_LABELS["klarna"],
        PAYMENT_LABELS["amazon_pay"],
        PAYMENT_LABELS["sepa_debit"],
        "PayPal Direktlink (ohne Stripe)",
        *(["Überweisung (SEPA)"] if sepa_info() else []),
    ]


def enrich_catalog(catalog: dict[str, dict]) -> dict[str, dict]:
    """PayPal-Links an Produktkatalog anhängen."""
    out: dict[str, dict] = {}
    for pid, prod in catalog.items():
        row = dict(prod)
        row["paypal_url"] = paypal_product_url(
            product_id=pid,
            price_eur=float(prod["price_eur"]),
            title=str(prod["name"]),
        )
        out[pid] = row
    return out
