"""
Nur verkaufen – keine neuen Produkt-Ordner mehr bauen.
Bestehende Produkte: Shop, Werbung, Kanäle, PayPal.
"""

from __future__ import annotations

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


def is_product_build_disabled(state: JamState) -> bool:
    return bool(
        getattr(state, "jam_no_product_build", False)
        or getattr(state, "jam_sell_only_mode", False)
        or getattr(state, "jam_sell_focus_mode", False)
    )


def apply_sell_without_build(brain: JamBrain, *, pace: int | None = None) -> str:
    """Jam baut keine neuen Produkte mehr – nur Verkauf & Werbung."""
    s = brain.state
    s.jam_no_product_build = True
    s.jam_sell_only_mode = True
    s.jam_sell_focus_mode = True
    s.jam_active_sell_mode = True
    s.jam_shop_heavy_promo = True
    s.jam_shop_always_on = True
    s.jam_programming_stopped = True
    s.jam_delegate_mode = False
    s.remember("Nur verkaufen – keine neuen Produkte bauen")
    s.last_action = "sell_without_build"
    brain.add_xp(5)
    brain.save()

    lines = [
        f"**{owner_name(s)}**, Jam **baut keine neuen Produkte** mehr.",
        "Stattdessen: **verkaufen + Werbung** für alles, was schon da ist.",
        "Shop, PayPal, Gumroad, Fiverr, schwere Shop-Werbung – **AN**.",
    ]
    if pace is not None:
        try:
            from jam.jam_pace import apply_pace

            lines.insert(1, apply_pace(brain, pace))
        except Exception:
            pass
    try:
        from jam.shop_heavy_promo import enable_heavy_promo

        lines.append(enable_heavy_promo(brain)[:240])
    except Exception as e:
        lines.append(f"Werbung: {e}")
    try:
        from jam.active_sell import apply_active_sell_startup

        apply_active_sell_startup(brain)
    except Exception:
        pass
    try:
        from jam.master_shop import shop_url, sync_stats_to_brain

        sync_stats_to_brain(brain)
        lines.append(f"Jam-Shop: {shop_url(brain.state)}")
    except Exception:
        pass
    return " ".join(lines)[:720]


def run_sell_instead_of_build(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """Verkaufs-Push ohne neues Produkt."""
    owner = owner_name(brain.state)
    parts: list[str] = []

    try:
        from jam.active_sell import maybe_active_sell_push, push_latest_products

        msg = maybe_active_sell_push(brain)
        if msg:
            parts.append(msg[:220])
        else:
            bit = push_latest_products(brain, max_items=2)
            if bit:
                parts.append(bit[:220])
    except Exception as e:
        parts.append(f"Verkauf: {e}"[:80])

    try:
        from jam.master_shop import sell_only_cycle

        bit, _ = sell_only_cycle(brain)
        if bit:
            parts.append(bit[:220])
    except Exception:
        pass

    if parts:
        return " ".join(parts)[:520]
    return (
        f"{owner}, **nur Verkauf** – ich baue nichts Neues. "
        "Teile den Shop-Link oder sag „aktiv verkaufen“ für die letzten Produkte."
    )[:480]


def hears_no_build_sell(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("nichts bauen", "nicht mehr bauen", "keine produkte", "kein produkt")):
        return True
    if any(w in h for w in ("bauen", "bau", "programmier")) and any(
        w in h for w in ("nicht", "kein", "stop", "aufhör", "aufhor")
    ):
        if any(w in h for w in ("verkauf", "verkaufen", "nur")):
            return True
    if "nur verkauf" in h or "nur verkaufen" in h:
        return True
    return False


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_no_build_sell(heard):
        return None
    h = heard.lower()
    pct = None
    m = __import__("re").search(r"(\d{2,3})\s*(?:%|prozent)", h)
    if m:
        pct = int(m.group(1))
    return apply_sell_without_build(brain, pace=pct)


def apply_startup(brain: JamBrain) -> None:
    if is_product_build_disabled(brain.state):
        brain.state.jam_no_product_build = True
        brain.save()
