"""
Massive Werbung für die Jam-Verkaufsseite – viele Kanäle, viele Texte, Auto-Loop.
"""

from __future__ import annotations

import json
import random
import time
import webbrowser
from datetime import datetime
from pathlib import Path
from urllib.parse import quote, quote_plus

from jam.brain import JamBrain, JamState
from jam.owner import owner_name
from jam.paypal_donate import PAYPAL_EMAIL

ROOT = Path(__file__).resolve().parent.parent
PROMO_ROOT = Path.home() / "Documents" / "Jam-Shop-Werbung"
HEAVY_GAP_SEC = 22.0
NORMAL_PROMO_GAP = 90.0
MAX_TABS_PER_ROUND = 12

KI_STUDIO = "https://ki-web-studio.de/"


def is_heavy_promo(state: JamState) -> bool:
    return bool(getattr(state, "jam_shop_heavy_promo", False))


def enable_heavy_promo(brain: JamBrain) -> str:
    brain.state.jam_shop_heavy_promo = True
    brain.state.jam_sell_only_mode = True
    brain.state.jam_no_product_build = True
    brain.state.last_action = "shop_heavy_promo_on"
    brain.state.remember("Jam macht VIEL Werbung für die Verkaufsseite")
    brain.save()
    from jam.master_shop import build_master_shop, start_shop_server

    build_master_shop(brain)
    url = start_shop_server(force=False)
    brain.state.jam_master_shop_url = url
    steps, n_posts = run_heavy_promo_round(brain, url, force=True)
    return (
        f"🔥 **Viel Werbung AN** für deine Jam-Seite! {len(steps)} Kanäle geöffnet, "
        f"{n_posts} Posts in {PROMO_ROOT}. Jam wiederholt alle ~{int(HEAVY_GAP_SEC)} Sek. "
        f"Shop: {url} · Stopp: „Werbung aus“"
    )[:680]


def disable_heavy_promo(brain: JamBrain) -> str:
    brain.state.jam_shop_heavy_promo = False
    brain.state.last_action = "shop_heavy_promo_off"
    brain.save()
    return "Werbung-Blitz beendet. Jam macht nur noch normale Shop-Promo."


def hears_heavy_promo(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("werbung", "werben", "bewerb", "promo", "marketing", "reichweite")):
        if any(
            w in h
            for w in (
                "viel",
                "mehr",
                "massiv",
                "richtig",
                "blitz",
                "überall",
                "kanal",
                "seite",
                "shop",
                "verkauf",
            )
        ):
            return True
    if "seite bewerben" in h or "shop bewerben" in h:
        return True
    if "werbung aus" in h or "werbung stop" in h or "weniger werbung" in h:
        return True
    return False


def share_texts(url: str, n_products: int, owner: str) -> list[str]:
    return [
        f"🤖 Jam-Shop – {n_products} digitale Produkte! PayPal-sicher kaufen: {url}",
        f"Neuer Shop von {owner}: Minecraft, Webseiten, Discord-Bots & mehr → {url}",
        f"Digitale Deals ab 0,99 € – Jam-Verkaufsseite: {url} (PayPal {PAYPAL_EMAIL})",
        f"🛒 {n_products}+ Angebote – One-Click PayPal. Schau rein: {url}",
        f"Freelancer-Tipps: Moderne Webseiten, MC-Server, Plugins – {url}",
        f"🇩🇪 Deutscher Digital-Shop – Jam für {owner}: {url}",
        f"Gaming & Code Shop – Sticker, Tools, Guides: {url}",
        f"Offizielle Jam-Seite LIVE – Dashboard zeigt Klicks: {url}dashboard.html",
        f"Auch Webdesign: ki-web-studio.de + Shop {url}",
        f"WhatsApp/Discord Freunde: Digital shoppen bei Jam → {url}",
        f"🔥 Limitiert: Jam baut & verkauft – du kaufst per PayPal: {url}",
        f"Portfolio, Minecraft, Python – alles hier: {url}webseiten.html",
    ]


def promo_links(url: str, text: str) -> list[tuple[str, str]]:
    enc = quote_plus(text[:280])
    enc_url = quote(url, safe="")
    return [
        ("Shop", url),
        ("Werbung-Seite", url + "werbung.html"),
        ("Webseiten", url + "webseiten.html"),
        ("Dienstleistungen", url + "dienstleistungen.html"),
        ("Demo-Web", url + "site/demo-index.html"),
        ("X / Twitter", f"https://twitter.com/intent/tweet?text={enc}"),
        ("WhatsApp", f"https://wa.me/?text={enc}"),
        ("Telegram Share", 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}"),
        ("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}"),
        (
            "Google: Shop teilen",
            f"https://www.google.com/search?q={quote_plus('digital products shop paypal deutsch')}",
        ),
        (
            "Google: Freelancer",
            f"https://www.google.com/search?q={quote_plus('günstige digitale produkte kaufen')}",
        ),
        ("Discord", "https://discord.com/channels/@me"),
        ("KI Web Studio", KI_STUDIO),
    ]


def write_promo_pack(
    *,
    url: str,
    owner: str,
    n_products: int,
    posts: 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)

    lines = [
        f"# Jam-Shop Werbung – {owner}",
        f"Shop: {url}",
        f"Produkte: {n_products}",
        f"Erstellt: {datetime.now().isoformat(timespec='seconds')}",
        "",
        "## Posts (kopieren & einfügen)",
        "",
    ]
    for i, p in enumerate(posts, 1):
        lines.append(f"### Post {i}\n{p}\n")

    (folder / "POSTS.md").write_text("\n".join(lines), encoding="utf-8")
    (folder / "posts.json").write_text(
        json.dumps({"url": url, "posts": posts}, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )

    latest = PROMO_ROOT / "AKTUELL.txt"
    latest.write_text(
        f"Letzte Werbe-Runde: {folder.name}\nShop: {url}\n\n" + "\n---\n".join(posts[:6]),
        encoding="utf-8",
    )
    return folder


def _copy_clipboard_win(text: str) -> bool:
    if len(text) > 4000:
        text = text[:4000]
    try:
        import subprocess

        subprocess.run(
            ["powershell", "-NoProfile", "-Command", f"Set-Clipboard -Value {json.dumps(text)}"],
            check=True,
            timeout=8,
            capture_output=True,
        )
        return True
    except Exception:
        return False


def run_heavy_promo_round(
    brain: JamBrain,
    url: str | None = None,
    *,
    force: bool = False,
) -> tuple[list[str], int]:
    from jam.master_shop import build_master_shop, collect_products, shop_url

    if not url:
        build_master_shop(brain)
        url = shop_url(brain.state)
    n = len(collect_products(brain))
    owner = owner_name(brain.state)
    posts = share_texts(url, n, owner)
    pick = random.choice(posts)

    if not force:
        from jam.jam_pace import gap_seconds

        gap = gap_seconds(brain.state, HEAVY_GAP_SEC)
        last = getattr(brain.state, "last_heavy_shop_promo_at", 0.0)
        if time.time() - last < gap:
            return [], 0

    steps: list[str] = []
    links = promo_links(url, pick)
    random.shuffle(links)
    for label, link in links[:MAX_TABS_PER_ROUND]:
        try:
            webbrowser.open(link, new=2)
            steps.append(label)
            time.sleep(0.35)
        except OSError:
            pass

    folder = write_promo_pack(url=url, owner=owner, n_products=n, posts=posts)
    brain.state.last_heavy_shop_promo_at = time.time()
    brain.state.heavy_shop_promo_rounds = int(getattr(brain.state, "heavy_shop_promo_rounds", 0)) + 1
    brain.state.last_master_shop_promo_at = time.time()
    brain.state.remember(f"Werbung Runde {brain.state.heavy_shop_promo_rounds}: {len(steps)} Tabs")

    if _copy_clipboard_win(pick):
        steps.append("Zwischenablage")

    try:
        from jam.telegram_sell import run_telegram_ads

        if random.random() < 0.4:
            run_telegram_ads(brain, user_initiated=False)
            steps.append("Telegram")
    except Exception:
        pass

    brain.save()
    return steps, len(posts)


def maybe_auto_heavy_promo(brain: JamBrain) -> str | None:
    if not is_heavy_promo(brain.state):
        return None
    from jam.jam_pace import gap_seconds

    if time.time() - getattr(brain.state, "last_heavy_shop_promo_at", 0.0) < gap_seconds(
        brain.state, HEAVY_GAP_SEC
    ):
        return None
    url = getattr(brain.state, "jam_master_shop_url", "") or ""
    if not url:
        from jam.master_shop import run_master_shop_mission

        return run_master_shop_mission(brain, user_initiated=False)
    steps, n = run_heavy_promo_round(brain, url)
    if not steps:
        return None
    owner = owner_name(brain.state)
    return (
        f"{owner}, Werbe-Blitz! {len(steps)} Kanäle für die Jam-Seite. "
        f"{n} Texte in Jam-Shop-Werbung. Shop: {url}"
    )[:220]


def build_werbung_html(
    products: list[dict],
    owner: str,
    shop: str,
    *,
    esc,
) -> str:
    n = len(products)
    posts = share_texts(shop, n, owner)
    post_blocks = ""
    for i, p in enumerate(posts[:10], 1):
        post_blocks += f"""
<div class="post-box">
  <h3>Post {i}</h3>
  <textarea readonly id="post{i}">{esc(p)}</textarea>
  <button type="button" onclick="copyPost('post{i}')">Kopieren</button>
</div>"""

    btn_rows = ""
    for label, link in promo_links(shop, posts[0])[:16]:
        btn_rows += f'<a class="btn sm" href="{esc(link)}" target="_blank" rel="noopener">{esc(label)}</a>\n'

    sample = products[:6]
    plist = "\n".join(
        f"<li><strong>{esc(p['title'])}</strong> – {p['price']:.2f} €</li>" for p in sample
    )

    return f"""<!DOCTYPE html>
<html lang="de"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Jam Werbung – viel Reichweite</title>
<style>
body{{font-family:Segoe UI;background:#0f172a;color:#e2e8f0;max-width:900px;margin:0 auto;padding:1.5rem}}
h1{{color:#a78bfa}} h2{{color:#c4b5fd;font-size:1.1rem;margin:1.5rem 0 .75rem}}
.btn{{display:inline-block;margin:.35rem;padding:12px 18px;background:#7c3aed;color:#fff;
text-decoration:none;border-radius:10px;font-weight:700;font-size:.88rem}}
.btn.sm{{padding:8px 14px;font-size:.8rem;background:#5b21b6}}
.btn.fire{{background:#dc2626;font-size:1rem}}
.post-box{{background:#1e293b;border-radius:12px;padding:1rem;margin:1rem 0;border:1px solid #334155}}
textarea{{width:100%;min-height:72px;background:#0f172a;color:#e2e8f0;border:1px solid #475569;
border-radius:8px;padding:.6rem;font-size:.85rem}}
button{{margin-top:.5rem;padding:8px 16px;background:#4ade80;color:#0f172a;border:none;
border-radius:8px;font-weight:700;cursor:pointer}}
.hint{{color:#94a3b8;font-size:.9rem}}
.grid-btns{{display:flex;flex-wrap:wrap;gap:.35rem}}
</style>
<script src="jam-stats.js"></script>
<script>
function copyPost(id) {{
  var t = document.getElementById(id);
  t.select(); t.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(t.value).catch(function(){{}});
  alert('Kopiert!');
}}
</script>
</head>
<body>
<h1>📣 Jam macht VIEL Werbung</h1>
<p class="hint">Shop: <a href="{esc(shop)}">{esc(shop)}</a> · {n} Produkte · PayPal {esc(PAYPAL_EMAIL)}</p>
<p><a class="btn fire" href="{esc(shop)}">🛒 Zur Jam-Seite</a>
<a class="btn" href="{esc(shop)}webseiten.html">Webseiten</a>
<a class="btn" href="{esc(shop)}dienstleistungen.html">Leistungen</a></p>

<h2>🔥 Ein Klick – Kanäle</h2>
<div class="grid-btns">{btn_rows}</div>

<h2>📋 Texte zum Kopieren</h2>
{post_blocks}

<h2>🤖 Jam automatisch</h2>
<p class="hint">Sag Jam: <strong>„Mach viel Werbung für die Seite“</strong> – dann öffnet Jam alle ~22 Sek. neue Tabs + legt Posts unter Documents/Jam-Shop-Werbung ab.</p>
<ul>{plist}</ul>
</body></html>"""


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_heavy_promo(heard):
        return None
    h = heard.lower()
    if any(w in h for w in ("aus", "stop", "stopp", "weniger", "ende")):
        return disable_heavy_promo(brain)
    return enable_heavy_promo(brain)
