"""
Jami-Dating – Werbe-Content, Share-Links und Werben-Seite.
"""

from __future__ import annotations

import html
import json
import random
import subprocess
import time
import urllib.parse
import webbrowser
from datetime import date, datetime, timedelta
from pathlib import Path
from urllib.parse import quote, quote_plus

from jam.jami_domain import resolve_site_url

ROOT = Path(__file__).resolve().parent.parent
MARKETING_DIR = ROOT / "data" / "jami-marketing"
PROMO_ROOT = Path.home() / "Documents" / "Jam-Dating-Werbung"
MAX_TABS = 14

SITE_URL = "https://www.jami-dating.de"
TAGLINE = "Echte Singles · 100 Gratis-Coins · Keine Fake-Moderatoren · 18+"

HASHTAGS_TIKTOK = "#dating #singles #datingdeutschland #jamidating #single #liebe #kennenlernen"
HASHTAGS_X = "#dating #singles #jamidating #Deutschland"

TIKTOK_SCRIPTS = [
    "Kennt ihr diese Dating-Seiten mit Chat-Moderatoren die vorgeben Singles zu sein? 😤 "
    "Jami-Dating nicht. Nur echte registrierte Nutzer. 100 Coins gratis – Link in Bio.",
    "Profil in 30 Sekunden. Swipen. Matchen. Chatten. 100 Gratis-Coins geschenkt 🪙 "
    "www.jami-dating.de – echte Leute, kein Bullshit.",
    "Bei uns siehst du Stadt UND Land auf dem Profil – plus Entfernung in km. "
    "Dating ohne Rätselraten. Jami-Dating.de 🇩🇪",
    "10 Coins pro Nachricht – transparent. Kein Abo-Zwang. 100 Coins gratis beim Start.",
    "POV: Du findest endlich eine Dating-App ohne Fake-Profile 🎯 Jami-Dating – kostenlos testen.",
    "Tinder-Features ✓ Aber: echte Nutzer, Herkunft sichtbar, faire Coin-Preise. "
    "Jami-Dating – neu aus Deutschland.",
    "Single? 18+? 100 Coins gratis holen 👇 jami-dating.de – in 30 Sek registriert.",
    "Melden & Blockieren eingebaut. Nur 18+. Keine Moderatoren. Dating wie es sein sollte.",
    "Swipe links, swipe rechts – aber nur echte Menschen auf der anderen Seite. Jami-Dating.de",
    "Dein Crush ist 12 km entfernt? Bei Jami siehst du Herkunft + Entfernung. Kein Rätselraten.",
]

SOCIAL_POSTS: list[tuple[str, str]] = [
    (
        "instagram",
        "💕 Neu: Jami-Dating – echte Singles, echte Dates.\n"
        "✓ 100 Gratis-Coins\n✓ Swipe & Match\n✓ Herkunft & km-Entfernung\n"
        "✓ Keine Chat-Moderatoren",
    ),
    (
        "facebook",
        "Neu aus Deutschland: Jami-Dating. Kostenlos registrieren, 100 Coins geschenkt, "
        "fair chatten (10 Coins/Nachricht). Echte Personen – garantiert ohne Chat-Moderatoren.",
    ),
    (
        "tiktok",
        "Dating ohne Fake-Moderatoren? Jami-Dating. 100 Coins gratis 🪙 Nur echte Nutzer. 18+",
    ),
    (
        "whatsapp",
        "Hey! Kurz was Neues: Jami-Dating – Dating ohne Fake-Profile. "
        "100 Coins gratis wenn du testen willst 🪙",
    ),
    (
        "x",
        "Neu: Jami-Dating 🇩🇪 Echte Singles, 100 Gratis-Coins, keine Chat-Moderatoren. "
        "Swipe · Match · Chat. 18+",
    ),
    (
        "linkedin",
        "Jami-Dating – deutsche Dating-Plattform mit transparentem Coin-Modell. "
        "Keine Abo-Falle, echte registrierte Nutzer, Herkunft & Entfernung sichtbar.",
    ),
    (
        "reddit",
        "Jami-Dating – neue deutsche Dating-Seite, nur echte Nutzer (keine Moderatoren). "
        "100 Gratis-Coins zum Testen. Feedback willkommen!",
    ),
    (
        "telegram",
        "💕 Jami-Dating – echte Singles. 100 Coins gratis. Keine Fake-Profile. jami-dating.de",
    ),
    (
        "pinterest",
        "Jami-Dating – Dating in Deutschland. Echte Personen, faire Coins, Swipe & Match.",
    ),
    (
        "instagram",
        "Genug von Fake-Profilen? Bei Jami chattest du nur mit echten registrierten Nutzern.\n"
        "Kostenlos starten · Profil in 30 Sekunden · 100 🪙 geschenkt",
    ),
    (
        "facebook",
        "Single und 18+? Jami-Dating: Swipen, matchen, chatten – 100 Coins geschenkt beim Start. "
        "Herkunft & km-Entfernung auf jedem Profil.",
    ),
    (
        "x",
        "100 Gratis-Coins 🪙 Swipe & Match · Herkunft sichtbar · Keine Moderatoren. "
        "Jami-Dating – kostenlos testen. 18+",
    ),
]

GOOGLE_ADS = [
    ("Headline 1", "Jami-Dating – Echte Singles"),
    ("Headline 2", "100 Gratis-Coins geschenkt"),
    ("Headline 3", "Keine Fake-Moderatoren"),
    ("Description", "Kostenlos registrieren. Swipe, Match, Chat. Herkunft & km sichtbar. Nur 18+."),
    ("Description 2", "Deutsche Dating-Plattform. Fair: 10 Coins pro Nachricht. Jetzt testen."),
]

SEVEN_DAY_SPRINT = [
    ("Tag 1", "TikTok Video [1] + Instagram Post 1 + WhatsApp an 5 Freunde"),
    ("Tag 2", "Facebook Post + X Post + Reddit r/de (ehrlicher Launch-Post)"),
    ("Tag 3", "TikTok Video [3] Herkunft-USP + Story mit Link-Sticker"),
    ("Tag 4", "Instagram Reel (POV-Skript) + Facebook Gruppe Singles DE"),
    ("Tag 5", "TikTok [7] CTA + LinkedIn Post (Business-Netzwerk teilen)"),
    ("Tag 6", "Alle Kanäle: '100 Coins gratis' Reminder + Telegram Kanäle"),
    ("Tag 7", "Review: welcher Post hat Klicks? UTM in Analytics prüfen"),
]


def site_url(*, with_www: bool = True) -> str:
    url = (resolve_site_url() or SITE_URL).rstrip("/")
    if with_www and "jami-dating.de" in url and "www." not in url:
        return "https://www.jami-dating.de"
    return url


def utm_url(
    platform: str,
    *,
    medium: str = "social",
    campaign: str = "launch",
    day: int | None = None,
) -> str:
    base = site_url()
    params: dict[str, str] = {
        "utm_source": platform,
        "utm_medium": medium,
        "utm_campaign": campaign,
    }
    if day is not None:
        params["utm_content"] = f"day{day}"
    return f"{base}/?{urllib.parse.urlencode(params)}"


def share_urls(text: str, url: str) -> dict[str, str]:
    """One-click Share-URLs für gängige Plattformen."""
    enc_url = urllib.parse.quote(url, safe="")
    enc_text = urllib.parse.quote(text, safe="")
    full = urllib.parse.quote(f"{text}\n{url}", safe="")
    return {
        "x": f"https://twitter.com/intent/tweet?text={enc_text}&url={enc_url}",
        "facebook": f"https://www.facebook.com/sharer/sharer.php?u={enc_url}",
        "whatsapp": f"https://wa.me/?text={full}",
        "telegram": f"https://t.me/share/url?url={enc_url}&text={enc_text}",
        "linkedin": f"https://www.linkedin.com/sharing/share-offsite/?url={enc_url}",
        "reddit": f"https://reddit.com/submit?url={enc_url}&title={enc_text}",
        "pinterest": (
            f"https://pinterest.com/pin/create/button/?url={enc_url}&description={enc_text}"
        ),
        "bluesky": f"https://bsky.app/intent/compose?text={full}",
        "mastodon": f"https://mastodon.social/share?text={full}",
        "email": (
            f"mailto:?subject={urllib.parse.quote('Jami-Dating – echte Singles')}"
            f"&body={full}"
        ),
    }


def pick_post(*, seed: int | None = None) -> tuple[str, str, str]:
    """(platform, body, full_url) für heute."""
    idx = (seed if seed is not None else date.today().toordinal()) % len(SOCIAL_POSTS)
    platform, body = SOCIAL_POSTS[idx]
    url = utm_url(platform, day=date.today().day)
    return platform, body, url


def pick_x_post() -> str:
    day = date.today().day
    posts = [p for plat, p in SOCIAL_POSTS if plat == "x"]
    body = posts[day % len(posts)]
    url = utm_url("x", day=day)
    text = f"{body}\n{url} {HASHTAGS_X}"
    return text[:280]


def pick_tiktok_script() -> str:
    idx = date.today().toordinal() % len(TIKTOK_SCRIPTS)
    script = TIKTOK_SCRIPTS[idx]
    url = utm_url("tiktok", medium="video", day=date.today().day)
    return f"{script}\n\n{url}\n{HASHTAGS_TIKTOK}"


def generate_calendar(days: int = 30) -> list[str]:
    lines: list[str] = []
    start = date.today()
    for i in range(days):
        d = start + timedelta(days=i)
        idx = (d.toordinal()) % len(SOCIAL_POSTS)
        platform, body = SOCIAL_POSTS[idx]
        tik_idx = d.toordinal() % len(TIKTOK_SCRIPTS)
        url = utm_url(platform, day=d.day)
        lines.append(f"=== {d.isoformat()} ({d.strftime('%A')}) ===")
        lines.append(f"Kanal: {platform.upper()}")
        lines.append(f"Post: {body}")
        lines.append(f"Link: {url}")
        lines.append(f"TikTok-Idee: {TIKTOK_SCRIPTS[tik_idx][:120]}…")
        lines.append("")
    return lines


def write_tiktok_last_post() -> Path:
    from jam.tiktok_studio import write_last_post

    script = pick_tiktok_script()
    post = {
        "niche": "jami-dating",
        "caption": script,
        "hook": TIKTOK_SCRIPTS[date.today().toordinal() % len(TIKTOK_SCRIPTS)][:80],
        "url": utm_url("tiktok", medium="video"),
        "account_hint": "Eigenes Jami-Dating TikTok oder @socialmedia.mentor",
    }
    write_last_post(post)
    return ROOT / "data" / "tiktok-last-post.json"


def write_marketing_bundle() -> Path:
    MARKETING_DIR.mkdir(parents=True, exist_ok=True)
    day = date.today().day

    lines = [
        f"JAMI-DATING MARKETING BLITZ – {date.today().isoformat()}",
        "=" * 50,
        TAGLINE,
        f"URL: {site_url()}",
        "",
        "--- HEUTE (Copy & Paste) ---",
        "",
        "--- TIKTOK ---",
        pick_tiktok_script(),
    ]
    for plat, body in SOCIAL_POSTS:
        url = utm_url(plat, day=day)
        lines.extend(["", f"--- {plat.upper()} ---", body, url])

    lines.extend(["", "--- TIKTOK SKRIPTE (alle) ---", ""])
    for i, s in enumerate(TIKTOK_SCRIPTS, 1):
        lines.append(f"[{i}] {s}")

    lines.extend(["", "--- GOOGLE ADS ---", ""])
    for label, text in GOOGLE_ADS:
        lines.append(f"{label}: {text}")
    lines.append(f"Final URL: {utm_url('google', medium='cpc', campaign='search')}")

    lines.extend(["", "--- 7-TAGE SPRINT ---", ""])
    for tag, task in SEVEN_DAY_SPRINT:
        lines.append(f"{tag}: {task}")

    out = MARKETING_DIR / "blitz-heute.txt"
    out.write_text("\n".join(lines) + "\n", encoding="utf-8")

    cal = MARKETING_DIR / "kalender-30-tage.txt"
    cal.write_text("\n".join(generate_calendar(30)) + "\n", encoding="utf-8")

    batch = MARKETING_DIR / "posts-rotation.json"
    batch.write_text(
        json.dumps(
            [
                {"platform": p, "body": b, "url": utm_url(p)}
                for p, b in SOCIAL_POSTS
            ],
            ensure_ascii=False,
            indent=2,
        ),
        encoding="utf-8",
    )
    return out


def _clipboard(text: str) -> bool:
    if len(text) > 4000:
        text = text[:4000]
    try:
        subprocess.run(
            ["powershell", "-NoProfile", "-Command", f"Set-Clipboard -Value {json.dumps(text)}"],
            check=True,
            timeout=8,
            capture_output=True,
        )
        return True
    except (OSError, subprocess.CalledProcessError):
        return False


def promo_links(body: str, url: str) -> list[tuple[str, str]]:
    """Alle Share- und Hilfs-Links für eine Werbe-Runde."""
    text = f"{body}\n{url}"
    enc = quote_plus(text[:500])
    enc_url = quote(url, safe="")
    base = site_url()
    return [
        ("Jami Start", base),
        ("Werben-Seite", f"{base}/werben"),
        ("Animierte Promo", f"{base}/promo"),
        ("Facebook-Anzeige", f"{base}/ad"),
        ("WhatsApp", f"https://wa.me/?text={enc}"),
        ("Telegram", f"https://t.me/share/url?url={enc_url}&text={enc}"),
        ("Facebook Share", f"https://www.facebook.com/sharer/sharer.php?u={enc_url}&quote={enc}"),
        ("X / Twitter", f"https://twitter.com/intent/tweet?text={enc}"),
        ("LinkedIn", f"https://www.linkedin.com/sharing/share-offsite/?url={enc_url}"),
        ("Reddit Submit", f"https://www.reddit.com/submit?url={enc_url}&title={enc}"),
        ("Pinterest", f"https://pinterest.com/pin/create/button/?url={enc_url}&description={enc}"),
        ("E-Mail", share_urls(body, url)["email"]),
        ("Facebook Gruppen", f"https://www.facebook.com/search/groups/?q={quote_plus('singles deutschland')}"),
        ("Instagram", "https://www.instagram.com/"),
        ("TikTok Upload", "https://www.tiktok.com/tiktokstudio/upload?from=upload"),
        ("Discord DM", "https://discord.com/channels/@me"),
    ]


def write_promo_round(*, body: str, url: str, opened: list[str]) -> Path:
    PROMO_ROOT.mkdir(parents=True, exist_ok=True)
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    folder = PROMO_ROOT / f"runde-{stamp}"
    folder.mkdir(parents=True, exist_ok=True)
    post_text = f"{body}\n{url}"
    (folder / "POST.md").write_text(
        f"# Jami-Dating Werbung\n\n{post_text}\n\nGeöffnet: {', '.join(opened)}\n",
        encoding="utf-8",
    )
    (folder / "posts.json").write_text(
        json.dumps({"body": body, "url": url, "opened": opened}, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    (PROMO_ROOT / "AKTUELL.txt").write_text(
        f"Letzte Runde: {folder.name}\n\n{post_text}\n\nKanäle: {', '.join(opened)}",
        encoding="utf-8",
    )
    return folder


def open_everywhere(*, include_x_compose: bool = True) -> tuple[list[str], str, str]:
    """
    Maximale Werbe-Runde: Tabs öffnen, Text in Zwischenablage, optional X-Compose.
    Returns (opened_labels, body, url).
    """
    platform, body, url = pick_post()
    post_text = f"{body}\n{url}"
    _clipboard(post_text)

    links = promo_links(body, url)
    random.shuffle(links)
    opened: list[str] = []
    for label, link in links[:MAX_TABS]:
        try:
            webbrowser.open(link, new=2)
            opened.append(label)
            time.sleep(0.4)
        except OSError:
            pass

    if include_x_compose:
        try:
            open_x_compose()
            opened.append("X-Compose+Clipboard")
        except Exception:
            pass

    write_promo_round(body=body, url=url, opened=opened)
    return opened, body, url


def open_share_blitz(*, max_tabs: int = 8) -> list[str]:
    """Öffnet Share-URLs im Browser – David klickt nur noch Posten."""
    platform, body, url = pick_post()
    urls = share_urls(body, url)
    order = [
        "whatsapp",
        "facebook",
        "x",
        "telegram",
        "linkedin",
        "reddit",
        "pinterest",
        "bluesky",
        "mastodon",
        "email",
    ]
    opened: list[str] = []
    for key in order[:max_tabs]:
        try:
            webbrowser.open(urls[key], new=2)
            opened.append(key)
        except OSError:
            pass
    return opened


def open_x_compose() -> str:
    from jam.x_studio import open_compose, setup_studio_folders, X_COMPOSE
    from datetime import datetime

    text = pick_x_post()
    setup_studio_folders()
    day_dir = Path.home() / "Documents" / "Jam-X-Posten" / datetime.now().strftime("%Y-%m-%d")
    day_dir.mkdir(parents=True, exist_ok=True)
    path = day_dir / f"jami-{datetime.now().strftime('%H%M%S')}.md"
    path.write_text(f"# Jami X Post\n\n```\n{text}\n```\n", encoding="utf-8")
    open_compose(text=text, also_home=False)
    return text


def werben_page_html(*, site_base: str | None = None) -> str:
    base = (site_base or site_url()).rstrip("/")
    url = utm_url("share", medium="referral", campaign="werben-page")
    short_text = (
        "Jami-Dating – echte Singles, 100 Gratis-Coins, keine Fake-Moderatoren. 18+"
    )
    shares = share_urls(short_text, url)

    def btn(label: str, href: str, cls: str) -> str:
        return (
            f'<a class="werben-btn werben-btn--{cls}" href="{href}" '
            f'target="_blank" rel="noopener noreferrer">{label}</a>'
        )

    posts_html = ""
    for plat, body in SOCIAL_POSTS[:8]:
        u = utm_url(plat)
        copy_val = html.escape(f"{body}\n{u}", quote=True)
        posts_html += f"""
        <article class="werben-card">
          <h3>{plat.upper()}</h3>
          <pre class="werben-copy">{html.escape(body)}</pre>
          <p class="werben-link"><a href="{u}" target="_blank" rel="noopener">{html.escape(u)}</a></p>
          <button type="button" class="werben-copy-btn" data-copy="{copy_val}">Text kopieren</button>
        </article>"""

    return f"""
<style>
.werben-hero {{ text-align:center; padding:2rem 1rem 1rem; }}
.werben-hero h1 {{ font-size:1.75rem; margin-bottom:0.5rem; }}
.werben-hero p {{ color:var(--muted,#666); max-width:36rem; margin:0 auto 1.5rem; }}
.werben-share {{ display:flex; flex-wrap:wrap; gap:0.6rem; justify-content:center; margin:1.5rem 0; }}
.werben-btn {{
  display:inline-block; padding:0.65rem 1.1rem; border-radius:999px;
  font-weight:600; text-decoration:none; font-size:0.95rem;
  background:var(--accent,#e91e63); color:#fff;
}}
.werben-btn--wa {{ background:#25d366; }}
.werben-btn--fb {{ background:#1877f2; }}
.werben-btn--x {{ background:#000; }}
.werben-btn--tg {{ background:#0088cc; }}
.werben-btn--li {{ background:#0a66c2; }}
.werben-grid {{ display:grid; gap:1rem; max-width:48rem; margin:0 auto; padding:0 1rem 2rem; }}
@media (min-width:640px) {{ .werben-grid {{ grid-template-columns:1fr 1fr; }} }}
.werben-card {{
  border:1px solid var(--border,#eee); border-radius:12px; padding:1rem;
  background:var(--card,#fff);
}}
.werben-card h3 {{ margin:0 0 0.5rem; font-size:0.85rem; letter-spacing:0.05em; }}
.werben-copy {{ white-space:pre-wrap; font-family:inherit; font-size:0.9rem;
  background:var(--bg,#f8f8f8); padding:0.75rem; border-radius:8px; margin:0 0 0.5rem; }}
.werben-copy-btn {{
  border:none; background:var(--accent,#e91e63); color:#fff; padding:0.4rem 0.9rem;
  border-radius:8px; cursor:pointer; font-weight:600;
}}
.werben-cta {{ text-align:center; padding:1rem; }}
.werben-cta a {{ font-size:1.1rem; font-weight:700; }}
</style>
<div class="werben-hero">
  <h1>Jami teilen &amp; werben</h1>
  <p>{TAGLINE}<br/>Hilf mit – ein Klick, fertiger Text. Ehrlich werben, keine Fake-Zahlen.</p>
  <div class="werben-share">
    {btn("WhatsApp", shares["whatsapp"], "wa")}
    {btn("Facebook", shares["facebook"], "fb")}
    {btn("X / Twitter", shares["x"], "x")}
    {btn("Telegram", shares["telegram"], "tg")}
    {btn("LinkedIn", shares["linkedin"], "li")}
    {btn("E-Mail", shares["email"], "mail")}
  </div>
  <p class="werben-cta"><a href="{base}/">→ Jetzt kostenlos registrieren</a></p>
</div>
<div class="werben-grid">{posts_html}</div>
<script>
document.querySelectorAll('.werben-copy-btn').forEach(function(btn) {{
  btn.addEventListener('click', function() {{
    var t = btn.getAttribute('data-copy') || '';
    navigator.clipboard.writeText(t).then(function() {{
      btn.textContent = 'Kopiert ✓';
      setTimeout(function() {{ btn.textContent = 'Text kopieren'; }}, 2000);
    }});
  }});
}});
</script>"""
