"""
Jami – Dating: verlieben, neue Leute treffen, Nähe + Herkunft, Coin-Monetarisierung.

Baut statische Seite nach Documents/Jam-Jami und startet lokalen Server.
"""

from __future__ import annotations

import json
import os
import threading
import webbrowser
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

from jam.operator_data import OPERATOR
from jam.owner import owner_name

SITE_ROOT = Path.home() / "Documents" / "Jam-Jami"
SITE_PORT = 8771
SITE_URL = f"http://127.0.0.1:{SITE_PORT}/"


def _oauth_config_from_secrets() -> dict[str, str | bool]:
    secrets_file = Path(__file__).resolve().parents[1] / "data" / "jami-secrets.local.json"
    if not secrets_file.is_file():
        return {"google": False, "facebook": False, "googleClientId": "", "facebookAppId": ""}
    try:
        s = json.loads(secrets_file.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return {"google": False, "facebook": False, "googleClientId": "", "facebookAppId": ""}
    gcid = str(s.get("google_client_id", "")).strip()
    gsec = str(s.get("google_client_secret", "")).strip()
    fbid = str(s.get("facebook_app_id", "")).strip()
    fbsec = str(s.get("facebook_app_secret", "")).strip()
    google_ok = bool(gcid and "HIER" not in gcid)
    facebook_ok = bool(fbid and fbsec and "HIER" not in fbid)
    return {
        "google": google_ok,
        "facebook": facebook_ok,
        "googleClientId": gcid if google_ok else "",
        "facebookAppId": fbid if fbid and "HIER" not in fbid else "",
        "googleHasSecret": bool(gsec and "HIER" not in gsec),
    }


def _beta_test_config_from_secrets() -> dict[str, str | int | bool]:
    secrets_file = Path(__file__).resolve().parents[1] / "data" / "jami-secrets.local.json"
    play_url = ""
    if secrets_file.is_file():
        try:
            s = json.loads(secrets_file.read_text(encoding="utf-8"))
            play_url = str(s.get("beta_test_play_url", "")).strip()
        except (OSError, json.JSONDecodeError):
            play_url = ""
    return {
        "enabled": True,
        "rewardCoins": 1000,
        "playStoreUrl": play_url if play_url.startswith("https://") else "",
    }


def paypal_coin_url(coins: int, price_eur: float) -> str:
    from urllib.parse import quote

    return (
        "https://www.paypal.com/cgi-bin/webscr?"
        f"cmd=_xclick&business={quote(OPERATOR['paypal'])}"
        f"&currency_code=EUR&amount={price_eur:.2f}"
        f"&item_name={quote(f'Jami {coins} Coins')}"
    )


def stripe_price_id_for_pack(pack_id: str) -> str:
    """Stripe Price-ID aus Umgebung (z. B. STRIPE_PRICE_KENNENLERN=price_…)."""
    key = pack_id.upper().replace("-", "_")
    return (
        os.environ.get(f"STRIPE_PRICE_{key}", "")
        or os.environ.get(f"STRIPE_PRICE_ID_{pack_id}", "")
    ).strip()


COIN_PACKS = (
    {
        "id": "starter",
        "coins": 100,
        "price": 2.99,
        "label": "Starter",
        "bonus": "≈10 Chat-Nachrichten",
        "badge": None,
        "featured": False,
    },
    {
        "id": "plus",
        "coins": 320,
        "price": 4.99,
        "label": "Plus",
        "bonus": "300 + 20 Bonus",
        "badge": None,
        "featured": False,
    },
    {
        "id": "pro",
        "coins": 780,
        "price": 9.99,
        "label": "Pro",
        "bonus": "700 + 80 Bonus · 👑 VIP Gold am Profil",
        "badge": "VIP GOLD",
        "vipGold": True,
        "featured": True,
    },
    {
        "id": "vip",
        "coins": 1600,
        "price": 19.99,
        "label": "VIP",
        "bonus": "1500 + 100 Bonus · 👑 VIP Gold am Profil",
        "badge": "VIP GOLD",
        "vipGold": True,
        "featured": False,
    },
)

MESSAGE_COST_PER_CHAT = 10
MATCH_FREE_MESSAGES = 2
VIP_GOLD_MIN_PRICE_EUR = 9.99
PROFILE_BOOST_COINS = 15
PROFILE_BOOST_MINUTES = 30
PHOTO_SLOTS_FREE_GALLERY = 4
PHOTO_SLOTS_MAX_GALLERY = 9
PHOTO_SLOT_GALLERY_COST = 20
PHOTO_SLOTS_FREE_LOCKED = 5
PHOTO_SLOTS_MAX_LOCKED = 10
PHOTO_SLOT_LOCKED_COST = 25
ACTIVITY_BADGE_FAST_REPLY_MAX_MIN = 20
ACTIVITY_BADGE_FAST_REPLY_MIN_SAMPLES = 3
ACTIVITY_BADGE_VERY_ACTIVE_HOURS = 24
ACTIVITY_BADGE_VERY_ACTIVE_MIN_MSGS_7D = 2
CHAT_PHOTO_MAX_CHARS = 480_000
MESSAGE_TIERS = (
    {"from": 1, "to": 9999, "cost": MESSAGE_COST_PER_CHAT, "label": "Jede Chat-Nachricht"},
)

EMOJI_SHOP = (
    {"id": "heart_big", "icon": "❤️", "name": "Großes Herz", "coins": 25, "anim": "pulse"},
    {"id": "fire", "icon": "🔥", "name": "Feuer-Boost", "coins": 30, "anim": "fire"},
    {"id": "sparkle", "icon": "✨", "name": "Sparkle-Paket", "coins": 20, "anim": "sparkle"},
    {"id": "rose", "icon": "🌹", "name": "Rose", "coins": 18, "anim": "sway"},
    {"id": "star", "icon": "⭐", "name": "Super-Stern", "coins": 22, "anim": "spin"},
    {"id": "vip_badge", "icon": "💎", "name": "VIP-Badge", "coins": 50, "anim": "glow"},
    {"id": "kiss", "icon": "💋", "name": "Kuss", "coins": 24, "anim": "wiggle"},
    {"id": "party", "icon": "🎊", "name": "Konfetti", "coins": 28, "anim": "bounce"},
    {"id": "cupid", "icon": "💘", "name": "Amors Pfeil", "coins": 27, "anim": "heartbeat"},
)

FREE_CHAT_EMOJIS = (
    "😀", "😊", "😂", "🥰", "😍", "😘", "😉", "🤗", "👍", "👋", "🙏", "💬",
    "❤️", "💕", "🔥", "✨", "🎉", "😢", "🤔", "💪", "🌹", "⭐",
)


def _legal_page(title: str, body_html: str) -> str:
    from jam.dating_site_assets import LOGO_MARKUP_HOME

    return f"""<!DOCTYPE html>
<html lang="de">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>{title} – Jami</title>
  <link rel="icon" href="images/jami-dating-logo.png" type="image/png"/>
  <link rel="apple-touch-icon" href="images/jami-dating-logo.png"/>
  <link rel="stylesheet" href="css/app.css"/>
</head>
<body class="legal-page">
  <header class="legal-header">
    {LOGO_MARKUP_HOME}
  </header>
  <main class="legal-main">{body_html}</main>
  <footer class="legal-footer">
    <a href="/">Start</a> · <a href="/impressum">Impressum</a> ·
    <a href="/datenschutz">Datenschutzerklärung</a> · <a href="/agb">AGB</a> ·
    <a href="/" onclick="if(window.JamiCookies){{JamiCookies.openSettings();return false;}}">Cookies</a>
  </footer>
  <script src="js/cookie-consent.js"></script>
</body>
</html>"""


def build_site(brain=None, *, site_url: str | None = None) -> Path:
    """Komplette Dating-Seite nach Documents/Jam-Herkunft-Dating."""
    from jam.jami_domain import resolve_site_url

    owner = owner_name(brain.state) if brain else "David"
    SITE_ROOT.mkdir(parents=True, exist_ok=True)
    (SITE_ROOT / "css").mkdir(exist_ok=True)
    (SITE_ROOT / "js").mkdir(exist_ok=True)
    (SITE_ROOT / "images").mkdir(exist_ok=True)

    config = {
        "paypal": OPERATOR["paypal"],
        "owner": owner,
        "coinPacks": [
            {
                **p,
                "url": paypal_coin_url(p["coins"], p["price"]),
                "stripePriceId": stripe_price_id_for_pack(p["id"]),
            }
            for p in COIN_PACKS
        ],
        "messageCostPerChat": MESSAGE_COST_PER_CHAT,
        "matchFreeMessages": MATCH_FREE_MESSAGES,
        "chatPhotoMaxChars": CHAT_PHOTO_MAX_CHARS,
        "messageTiers": MESSAGE_TIERS,
        "emojiShop": EMOJI_SHOP,
        "freeChatEmojis": FREE_CHAT_EMOJIS,
        "signupBonusCoins": 50,
        "profileCompleteBonusCoins": 10,
        "presenceOnlineMinutes": 5,
        "presenceRecentMinutes": 30,
        "presenceDotHours": 24,
        "presenceWeekDays": 7,
        "presenceHeartbeatSec": 45,
        "superLikeCost": 8,
        "profileBoostCoins": PROFILE_BOOST_COINS,
        "profileBoostMinutes": PROFILE_BOOST_MINUTES,
        "photoSlotsFreeGallery": PHOTO_SLOTS_FREE_GALLERY,
        "photoSlotsMaxGallery": PHOTO_SLOTS_MAX_GALLERY,
        "photoSlotGalleryCost": PHOTO_SLOT_GALLERY_COST,
        "photoSlotsFreeLocked": PHOTO_SLOTS_FREE_LOCKED,
        "photoSlotsMaxLocked": PHOTO_SLOTS_MAX_LOCKED,
        "photoSlotLockedCost": PHOTO_SLOT_LOCKED_COST,
        "chatStatusPollSec": 5,
        "chatTypingTtlSec": 5,
        "inboxPollSec": 25,
        "activityBadges": {
            "fastReplyMaxMinutes": ACTIVITY_BADGE_FAST_REPLY_MAX_MIN,
            "fastReplyMinSamples": ACTIVITY_BADGE_FAST_REPLY_MIN_SAMPLES,
            "veryActiveHours": ACTIVITY_BADGE_VERY_ACTIVE_HOURS,
            "veryActiveMinMsgs7d": ACTIVITY_BADGE_VERY_ACTIVE_MIN_MSGS_7D,
        },
        "adReward": {
            "enabled": True,
            "freeInstant": False,
            "coinsPerVideo": 1,
            "secondsWatch": 15,
            "dailyMax": 10,
            "youtubeVideoIds": [
                "jfKfPfyJRdk",
                "5qap5aOk4XI",
                "DWcJFN3fqz0",
            ],
        },
        "shopWelcome": {
            "bonusCoinsPerPack": 40,
            "countdownMinutes": 15,
            "newUserHours": 24,
        },
        "siteUrl": (site_url or resolve_site_url()).rstrip("/"),
        "referralBonusCoins": 35,
        "tagline": "Nur echte Personen – keine Chat-Moderatoren",
        "backend": "cloudflare",
        "vapidPublicKey": (os.environ.get("JAMI_VAPID_PUBLIC_KEY") or os.environ.get("VAPID_PUBLIC_KEY") or "").strip(),
        "pushEnabled": bool((os.environ.get("JAMI_VAPID_PUBLIC_KEY") or os.environ.get("VAPID_PUBLIC_KEY") or "").strip()),
        "oauth": _oauth_config_from_secrets(),
        "betaTest": _beta_test_config_from_secrets(),
    }
    (SITE_ROOT / "js" / "config.json").write_text(
        json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8"
    )

    from jam.dating_site_assets import write_assets
    from jam.jami_legal import datenschutz_html, impressum_html, test_checklist_text

    site_url = config["siteUrl"]
    impressum = _legal_page("Impressum", impressum_html(OPERATOR, site_url=site_url))
    (SITE_ROOT / "impressum.html").write_text(impressum, encoding="utf-8")

    datenschutz = _legal_page(
        "Datenschutzerklärung",
        datenschutz_html(OPERATOR, site_url=site_url),
    )
    (SITE_ROOT / "datenschutz.html").write_text(datenschutz, encoding="utf-8")

    from jam.jami_app_page import app_page_body_html, copy_apk_to_site
    from jam.jami_marketing import werben_page_html

    apk_on_site = copy_apk_to_site(SITE_ROOT)

    werben = _legal_page("Werben & teilen", werben_page_html(site_base=site_url))
    (SITE_ROOT / "werben.html").write_text(werben, encoding="utf-8")

    from jam.jami_animated_ad import animated_promo_page_html, facebook_style_ad_html

    (SITE_ROOT / "promo.html").write_text(
        animated_promo_page_html(site_base=site_url), encoding="utf-8"
    )
    (SITE_ROOT / "ad.html").write_text(
        facebook_style_ad_html(site_base=site_url), encoding="utf-8"
    )

    app_page = _legal_page("App installieren", app_page_body_html(apk_on_site=apk_on_site))
    (SITE_ROOT / "app.html").write_text(app_page, encoding="utf-8")

    agb = _legal_page(
        "AGB",
        """
<h1>AGB & Coin-Hinweise</h1>
<p><strong>1. Leistung</strong> Jami vermittelt Kontakte zum Kennenlernen und Verlieben. Kein Erfolgsversprechen.</p>
<p><strong>2. Coins</strong> Virtuelle Währung nur auf der Plattform. Keine Rückerstattung nach Nutzung,
außer bei gesetzlichem Widerrufsrecht (digitale Güter: Einwilligung vor Vertragsschluss).</p>
<p><strong>3. Preise</strong> Coin-Pakete ab 2,99 € (100 Coins). Jede Chat-Nachricht: 10 Coins.
Pakete: Plus 4,99 € (320 Coins), Pro 9,99 € (780), VIP 19,99 € (1600). Ab Pro (9,99 €) inklusive
<strong>VIP Gold-Status</strong> mit Krone am Profil. Emoji/Icons und zusätzliche
Fotoplätze (öffentlich/privat) kosten extra Coins im Profil.</p>
<p><strong>4. Zahlung (Stripe)</strong> Coin-Käufe können per Stripe Checkout bezahlt werden:
Kredit-/Debitkarte, SEPA-Lastschrift, Klarna und PayPal (je nach Freigabe im Stripe-Konto).
Anbieter: Stripe Payments Europe Ltd. – <a href="https://stripe.com/de/privacy" target="_blank" rel="noopener">Stripe Datenschutz</a>.
Coins werden nach erfolgreicher Zahlung automatisch gutgeschrieben.</p>
<p><strong>5. Zahlungsabwicklung</strong> Alle Coin-Käufe laufen über Stripe Checkout.
Coins werden nur nach bestätigter Zahlung automatisch gutgeschrieben.</p>
<p><strong>6. Nur echte Personen</strong> Jami setzt keine Chat-Moderatoren, keine Fake-Profile
und keine „Animatoren“ ein, die vorgeben, Nutzer zu sein. Chats finden ausschließlich zwischen
registrierten Nutzerinnen und Nutzern statt. Verstöße (Fake-Identität, Belästigung) führen zur Sperre.</p>
<p><strong>7. Fotos</strong> Öffentlich: Hauptfoto und 4 weitere Fotos. Fünf private Fotos sind erst nach
angenommener Freundschaftsanfrage sichtbar – dort sind auch <strong>Nacktfotos ab 18 Jahren</strong> erlaubt.
Keine Fotos von Minderjährigen oder ohne Einwilligung der abgebildeten Person.</p>
<p><strong>8. Kontaktdaten</strong> Telefonnummern und E-Mail-Adressen dürfen in Profiltexten und Chats
<strong>nicht veröffentlicht</strong> werden (werden technisch verborgen). Kommunikation läuft über Jami.</p>
<p><strong>9. Pflichten</strong> Keine Belästigung, keine Minderjährigen, nur 18+.</p>
""",
    )
    (SITE_ROOT / "agb.html").write_text(agb, encoding="utf-8")

    (SITE_ROOT / "JAMI_TESTEN.txt").write_text(
        test_checklist_text(site_url=site_url), encoding="utf-8"
    )

    write_assets(SITE_ROOT, site_url=site_url)

    from jam.jami_seo_pages import write_seo_pages

    seo_urls = write_seo_pages(SITE_ROOT, site_url=site_url)
    (SITE_ROOT / "SEO_PASSIV.txt").write_text(
        f"Automatische SEO-Seiten: {len(seo_urls)} URLs\n"
        f"Sitemap: {site_url}/sitemap.xml\n"
        "Cron pingt IndexNow nach Deploy.\n",
        encoding="utf-8",
    )

    from jam.micro_tools_site import embed_micro_tools

    embed_micro_tools(SITE_ROOT)

    (SITE_ROOT / "DAVID_LESEN.txt").write_text(
        f"""JAMI – Verlieben & neue Leute treffen
====================================

Start: {SITE_URL}
Ordner: {SITE_ROOT}

Jami: Die Seite, wo man sich verlieben kann und neue Menschen trifft.

Mehrwert:
- Nutzer sehen ENTFERNUNG + HERKUNFT (Stadt/Land)
- Jede Chat-Nachricht: 10 Coins
- Emoji/Icon-Shop (großes Herz, VIP …)
- Coin-Kauf per Stripe Checkout (Karte, SEPA, Klarna, PayPal je nach Freigabe)

Coins werden nach erfolgreicher Zahlung automatisch gutgeschrieben.

Rechtliches: impressum.html, datenschutz.html, agb.html

Stand: Jam für {owner}
""",
        encoding="utf-8",
    )
    return SITE_ROOT


def start_server(*, open_browser: bool = True) -> str:
    if not (SITE_ROOT / "index.html").is_file():
        build_site()
    handler = lambda *a, **k: SimpleHTTPRequestHandler(*a, directory=str(SITE_ROOT), **k)
    server = ThreadingHTTPServer(("127.0.0.1", SITE_PORT), handler)

    def run():
        server.serve_forever()

    threading.Thread(target=run, daemon=True).start()
    if open_browser:
        try:
            webbrowser.open(SITE_URL, new=2)
        except OSError:
            pass
    return SITE_URL


def run_dating_mission(brain=None, *, user_initiated: bool = True) -> str:
    build_site(brain)
    url = start_server(open_browser=user_initiated)
    owner = owner_name(brain.state) if brain else "David"
    if brain:
        brain.state.remember("Jami Dating-Seite gebaut")
        brain.state.last_action = "dating_site"
        brain.save()
    return (
        f"{owner}, **Jami** ist fertig! **Verlieben & neue Leute** – mit **Nähe + Herkunft**, "
        f"**Coin-System** (Pakete ab 2,99 €, PayPal), 10 Coins pro Chat-Nachricht, 100 Coins Startbonus. "
        f"URL: {url} · Ordner: {SITE_ROOT.name}"
    )[:720]
