"""
Reichweite für Jam-Shop aufbauen: öffentlicher Link, Werbung, Social, KI Web Studio.
"""

from __future__ import annotations

import time
import webbrowser

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

REACH_ROOT = __import__("pathlib").Path.home() / "Documents" / "Jam-Reichweite"


def hears_reach(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    return any(
        w in h
        for w in (
            "reichweite",
            "reichweiten",
            "mehr kunden",
            "mehr besucher",
            "bekannter",
            "verbreit",
            "teilen",
            "weltweit",
            "öffentlich",
            "oeffentlich",
        )
    ) and any(w in h for w in ("bau", "mach", "auf", "jam", "shop", "seite", "verkauf"))


def build_reach(brain: JamBrain, *, open_browser: bool = True) -> str:
    """Volle Reichweite-Runde: Tunnel + Werbung + Märkte."""
    owner = owner_name(brain.state)
    state = brain.state
    parts: list[str] = [f"{owner}, ich baue **Reichweite** für deinen Jam-Shop auf!"]

    state.jam_sell_only_mode = True
    state.jam_no_product_build = True
    state.jam_shop_heavy_promo = True
    state.jam_active_sell_mode = True
    state.jam_shop_always_on = True
    brain.save()

    shop_url = ""
    try:
        from jam.shop_online import publish_shop_worldwide, get_public_shop_url

        parts.append(publish_shop_worldwide(brain, open_browser=False)[:280])
        shop_url = get_public_shop_url(brain.state) or ""
    except Exception as e:
        parts.append(f"Online-Link: {e}"[:120])

    if not shop_url:
        from jam.master_shop import build_master_shop, start_shop_server, shop_url as local_url

        build_master_shop(brain)
        shop_url = start_shop_server(force=False)
        state.jam_master_shop_url = shop_url

    if not getattr(state, "jam_master_shop_public_url", ""):
        parts.append(
            "**Öffentlicher Link:** Ordner Jam-Shop-Alles auf "
            "https://app.netlify.com/drop ziehen (Netlify öffnet sich)."
        )
        try:
            import webbrowser
            from jam.master_shop import SHOP_ROOT

            webbrowser.open("https://app.netlify.com/drop", new=2)
            webbrowser.open(str(SHOP_ROOT), new=0)
        except OSError:
            pass

    try:
        from jam.shop_heavy_promo import enable_heavy_promo, run_heavy_promo_round

        if not getattr(state, "jam_shop_heavy_promo", False):
            enable_heavy_promo(brain)
        steps, n_posts = run_heavy_promo_round(brain, shop_url, force=True)
        parts.append(f"Werbung: {len(steps)} Kanäle, {n_posts} Posts.")
    except Exception as e:
        parts.append(f"Werbung: {e}"[:80])

    try:
        from jam.world_earn import run_world_earn_round

        parts.append(run_world_earn_round(brain, user_initiated=True)[:200])
    except Exception as e:
        parts.append(f"Welt-Kanäle: {e}"[:80])

    try:
        from jam.ki_web_studio import present_ki_web_studio

        parts.append(present_ki_web_studio(brain)[:120])
    except Exception:
        webbrowser.open("https://ki-web-studio.de/", new=2)
        parts.append("ki-web-studio.de geöffnet (Vertrauen + Traffic).")

    REACH_ROOT.mkdir(parents=True, exist_ok=True)
    plan = REACH_ROOT / "REICHWEITE_PLAN.txt"
    public = getattr(state, "jam_master_shop_public_url", "") or shop_url
    plan.write_text(
        f"# Jam Reichweite – {time.strftime('%d.%m.%Y %H:%M')}\n\n"
        f"Shop (öffentlich): {public or '— Tunnel einrichten (ngrok/Netlify)'}\n"
        f"Shop (lokal): {shop_url}\n\n"
        "## David – 3 Schritte (wichtig)\n"
        "1. Öffentlichen Link in WhatsApp / Discord / Torchwood-Bio posten\n"
        "2. X/Twitter-Intent aus Jam-Shop-Werbung/POSTS.md nutzen\n"
        "3. ki-web-studio.de im Profil verlinken → Shop-Link\n\n"
        "## Jam macht automatisch\n"
        "- Viel-Werbung-Modus (wiederholt)\n"
        "- Weltweit-Kanäle (Gumroad, Fiverr, …)\n"
        "- Aktiv verkaufen\n\n"
        f"PayPal: david.prechtel1986@gmail.com\n",
        encoding="utf-8",
    )
    (REACH_ROOT / "AKTUELLER_SHOP_LINK.txt").write_text(
        (public or shop_url) + "\n", encoding="utf-8"
    )

    state.jam_reach_build_at = time.time()
    state.jam_reach_build_count = int(getattr(state, "jam_reach_build_count", 0)) + 1
    state.remember(f"Reichweite aufgebaut: {public[:50] if public else shop_url}")
    state.last_action = "reach_build"
    brain.add_xp(15)
    brain.save()

    if open_browser:
        try:
            if public:
                webbrowser.open(public, new=2)
            webbrowser.open(shop_url + "werbung.html", new=2)
            webbrowser.open(str(plan), new=0)
        except OSError:
            pass

    parts.append(f"Plan: {plan}")
    return " ".join(parts)[:720]


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_reach(heard):
        return None
    return build_reach(brain, open_browser=True)
