"""Dialog Studio Shop – Zeitpässe, PayPal, Überweisung, LAN-Werbung."""

from __future__ import annotations

import json
import socket
import time
from datetime import datetime
from pathlib import Path
from urllib.parse import quote

from jam.jampulse_brand import PRODUCT_BRAND
from jam.jampulse_payments import paypal_email, paypal_product_url, sepa_info
from jam.wan2gp_local import local_ip

ROOT = Path(__file__).resolve().parents[1]
STUDIO_PORT = 8793

# Nur Zeitpässe – unbegrenzt Videos im Zeitraum
DIALOG_PASSES: dict[str, dict] = {
    "dialog_week": {
        "name": f"{PRODUCT_BRAND} – 1 Woche",
        "price_eur": 6.99,
        "days": 7,
        "description": "7 Tage unbegrenzt · 3D-Dialog · Lip-Sync · WLAN für Freunde",
    },
    "dialog_month": {
        "name": f"{PRODUCT_BRAND} – 1 Monat",
        "price_eur": 19.99,
        "days": 31,
        "description": "31 Tage unbegrenzt · ~0,65 €/Tag · alle Features",
    },
    "dialog_6months": {
        "name": f"{PRODUCT_BRAND} – 6 Monate",
        "price_eur": 89.99,
        "days": 183,
        "description": "6 Monate unbegrenzt · ~15 €/Monat · Sparpass",
    },
    "dialog_year": {
        "name": f"{PRODUCT_BRAND} – 1 Jahr",
        "price_eur": 149.99,
        "days": 366,
        "description": "12 Monate unbegrenzt · ~12,50 €/Monat · bester Deal",
    },
}


def dialog_product_catalog() -> dict[str, dict]:
    """Zeitpässe: 1 Woche, 1 Monat, 6 Monate, 1 Jahr."""
    week = float(DIALOG_PASSES["dialog_week"]["price_eur"])
    month = float(DIALOG_PASSES["dialog_month"]["price_eur"])
    out: dict[str, dict] = {}
    for pid, row in DIALOG_PASSES.items():
        price = float(row["price_eur"])
        days = int(row["days"])
        per_day = price / max(days, 1)
        save_note = ""
        if pid == "dialog_month":
            baseline = week * (days / 7)
            if baseline > price:
                save_note = f" · spare {int(round((1 - price / baseline) * 100))} % vs. Wochenpass"
        elif pid == "dialog_6months":
            baseline = month * 6
            if baseline > price:
                save_note = f" · spare {baseline - price:.0f} € vs. 6× Monat"
        elif pid == "dialog_year":
            baseline = month * 12
            if baseline > price:
                save_note = f" · spare {baseline - price:.0f} € vs. 12× Monat"
        desc = str(row["description"])
        if save_note and save_note not in desc:
            desc = desc.rstrip(" ·") + save_note
        out[pid] = {
            "name": row["name"],
            "price_eur": price,
            "mode": "payment",
            "days": days,
            "description": desc,
            "per_day_eur": round(per_day, 2),
        }
    return out


def price_eur_de(amount: float) -> str:
    """6.99 → 6,99 €"""
    return f"{amount:.2f}".replace(".", ",") + " €"


def _enrich_dialog_catalog(catalog: dict[str, dict]) -> dict[str, dict]:
    ip = local_ip()
    base = f"http://{ip}:{STUDIO_PORT}/"
    out: dict[str, dict] = {}
    for pid, prod in catalog.items():
        row = dict(prod)
        return_url = f"{base}?paid=paypal&product={quote(pid)}"
        row["paypal_url"] = paypal_product_url(
            product_id=pid,
            price_eur=float(prod["price_eur"]),
            title=str(prod["name"]),
            return_url=return_url,
        )
        out[pid] = row
    return out


def pricing_public() -> dict:
    from jam.jampulse_license import license_status

    cat = _enrich_dialog_catalog(dialog_product_catalog())
    bank = sepa_info()
    ip = local_ip()
    return {
        "brand": PRODUCT_BRAND,
        "currency": "EUR",
        "license": license_status(),
        "products": [
            {
                "id": pid,
                "name": p["name"],
                "price_eur": p["price_eur"],
                "days": p.get("days"),
                "per_day_eur": p.get("per_day_eur"),
                "description": p.get("description", ""),
                "paypal_url": p.get("paypal_url", ""),
            }
            for pid, p in cat.items()
        ],
        "free_note": f"1× Gratis-Testvideo mit VidPuls-Hinweis – danach Zeitpass ab {DIALOG_PASSES['dialog_week']['price_eur']:.2f} €.",
        "payment_methods": [
            "PayPal (sofort)",
            "Karte · Apple Pay · Google Pay (Stripe)",
            "SEPA-Lastschrift (Stripe)",
            "EU-Banküberweisung (Stripe Checkout – IBAN automatisch)",
            *(["Manuelle Überweisung (SEPA)"] if bank else []),
        ],
        "paypal_email": paypal_email(),
        "bank_transfer": bank,
        "lan_url": f"http://{ip}:{STUDIO_PORT}/",
        "local_url": f"http://127.0.0.1:{STUDIO_PORT}/",
    }


def checkout(product_id: str, *, email: str = "", pay_with: str = "all") -> dict:
    from jam.jampulse_checkout import create_dialog_checkout

    return create_dialog_checkout(product_id, email=email, pay_with=pay_with)


def verify_stripe_return(session_id: str) -> dict:
    from jam.jampulse_checkout import verify_session

    return verify_session(session_id)


def verify_paypal_return(product_id: str, *, tx: str = "") -> dict:
    """Nach PayPal-Rückkehr Lizenz freischalten (tx verhindert Doppelbuchung)."""
    cat = dialog_product_catalog()
    pid = (product_id or "").strip()
    if pid not in cat:
        return {"ok": False, "error": f"Unbekanntes Produkt: {pid}"}

    from jam.jampulse_license import apply_purchase, load_license, save_license

    lic = load_license()
    used = list(lic.get("paypal_tx_ids") or [])
    txn = (tx or "").strip()
    if txn:
        if txn in used:
            return {
                "ok": True,
                "productId": pid,
                "license": lic,
                "message": "PayPal-Zahlung war schon freigeschaltet",
            }
    else:
        recent = float(lic.get("last_paypal_unlock_at") or 0)
        if recent > time.time() - 120 and lic.get("last_paypal_product") == pid:
            return {
                "ok": True,
                "productId": pid,
                "license": lic,
                "message": "Gerade freigeschaltet",
            }

    try:
        lic = apply_purchase(pid, session_id=f"paypal:{txn or int(time.time())}")
    except ValueError as e:
        return {"ok": False, "error": str(e)}

    lic = load_license()
    if txn:
        used.append(txn)
        lic["paypal_tx_ids"] = used[-80:]
    lic["last_paypal_product"] = pid
    lic["last_paypal_unlock_at"] = time.time()
    save_license(lic)
    return {"ok": True, "productId": pid, "license": lic}


def enable_lan_firewall(port: int = STUDIO_PORT) -> tuple[bool, str]:
    from jam.vidpuls_lan import enable_port_firewall

    return enable_port_firewall(port)


def export_werbung(out_dir: Path | None = None) -> Path:
    """Werbung + Preisliste auf Desktop/VidPuls legen."""
    try:
        from jam.jampulse_desktop import studio_root

        base = studio_root() / "Shop"
    except ImportError:
        base = Path.home() / "Desktop" / "VidPuls" / "Shop"
    if out_dir:
        base = out_dir
    base.mkdir(parents=True, exist_ok=True)

    pr = pricing_public()
    from jam.dialog_marketing import export_program_werbung

    export_program_werbung(base, lan_url=str(pr.get("lan_url") or ""))
    from jam.clipwelle_legal import write_legal_pages
    from jam.jampulse_brand import PRODUCT_SITE_URL

    write_legal_pages(base, site_url=PRODUCT_SITE_URL.rstrip("/"))
    lines = [
        f"{PRODUCT_BRAND} – Dating-Videos mit 3D-Figuren (Lip-Sync)",
        "=" * 52,
        "",
        "PREISE (Zeitpässe):",
    ]
    for p in pr["products"]:
        lines.append(f"  • {p['name']}: {p['price_eur']:.2f} €")
        lines.append(f"    PayPal: {p['paypal_url']}")
        lines.append("")
    lines.extend(
        [
            "ZAHLUNG:",
            "  • PayPal – sofort nach Zahlung Video erstellen",
            "  • Karte / SEPA / Überweisung – über Stripe Checkout (automatische IBAN)",
            "",
            f"Für Freunde im WLAN: {pr['lan_url']}",
            f"PayPal an: {pr['paypal_email']}",
            "",
            "HASHTAGS: #dating #jami #ki #videomarketing #tiktok #single",
        ]
    )
    if pr.get("bank_transfer"):
        b = pr["bank_transfer"]
        lines.extend(
            [
                "",
                "ÜBERWEISUNG (manuell):",
                f"  Empfänger: {b.get('holder')}",
                f"  IBAN: {b.get('iban')}",
                f"  {b.get('note', '')}",
            ]
        )

    txt = base / "WERBUNG-DIALOG-STUDIO.txt"
    txt.write_text("\n".join(lines) + "\n", encoding="utf-8")

    html = base / "werbung-snippet.html"
    prods_html = "".join(
        f'<li><strong>{p["name"]}</strong> – {p["price_eur"]:.2f} € '
        f'<a href="{p["paypal_url"]}">PayPal</a></li>'
        for p in pr["products"]
    )
    week_price = DIALOG_PASSES["dialog_week"]["price_eur"]
    html.write_text(
        f"""<!-- {PRODUCT_BRAND} Werbung einbetten -->
<section style="font-family:system-ui;max-width:520px;margin:1rem auto;padding:1.25rem;border-radius:16px;background:linear-gradient(135deg,#1a0a28,#0c0612);color:#fff">
<h2 style="margin:0 0 .5rem">3D Dating-Videos ab {week_price:.2f} €/Woche</h2>
<p style="opacity:.85;margin:0 0 1rem">Zeitpass · unbegrenzt · Lip-Sync · TikTok 9:16</p>
<ul style="line-height:1.8">{prods_html}</ul>
<p style="font-size:.85rem;opacity:.7">PayPal · Karte · SEPA · Überweisung</p>
</section>
""",
        encoding="utf-8",
    )
    (base / "preise.json").write_text(
        json.dumps(pr, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    return txt


def studio_port_open(host: str = "127.0.0.1") -> bool:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.settimeout(0.4)
        return s.connect_ex((host, STUDIO_PORT)) == 0
