"""Jam nutzt alle Verdienst-Kanäle – Cent für Cent wird reich."""

from __future__ import annotations

import random
import time

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

AUTO_GAP_SEC = 85.0
USER_GAP_SEC = 35.0
BURST_GAP_SEC = 200.0

PHILOSOPHY = (
    "Jeder Cent zählt – viele kleine Erfolge machen uns reich!",
    "0,99 € mal tausend ist auch ein Business, {owner}!",
    "Ich nehm **jeden** legalen Weg – Cent sind Erfolg!",
)

LINES = (
    "{owner}, **Max-Verdienen**: ich nutze alle Kanäle – auch Cent-Beträge!",
    "Cha-Ching-Modus! Verkauf, PayPal, Cursor, Umfragen, Micro-Shop – alles!",
    "{owner}, Cent für Cent – der Erfolg macht uns reich!",
)

DONE = (
    "Fertig: {n} Aktionen. Potenzial diese Runde ~{sum:.2f} € (auch Cent!).",
    "Runde abgeschlossen – {n} Wege genutzt, Summe ~{sum:.2f} € Schätzung.",
)


def apply_max_earn_startup(brain: JamBrain) -> None:
    brain.state.jam_max_earn_mode = True
    try:
        from jam.world_earn import apply_world_earn_startup

        apply_world_earn_startup(brain)
    except Exception:
        pass
    brain.save()


def hears_max_earn(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("max verdien", "alles verdien", "alle möglich", "alle moeglich")):
        return True
    if "reich" in h and any(w in h for w in ("cent", "geld", "verdien", "werden")):
        return True
    if "cent" in h and any(w in h for w in ("verdien", "reich", "nutz")):
        return True
    if "jeder cent" in h or "jeden cent" in h:
        return True
    if "geld verdienen" in h and any(w in h for w in ("alles", "alle", "möglich", "moeglich", "max")):
        return True
    if any(w in h for w in ("alles dran", "an geld kommen", "dran setzen")):
        return True
    try:
        from jam.world_earn import hears_world_earn

        if hears_world_earn(text):
            return True
    except Exception:
        pass
    return False


def _gap_ok(state: JamState, *, user: bool) -> tuple[bool, str]:
    gap = USER_GAP_SEC if user else AUTO_GAP_SEC
    last = getattr(state, "last_max_earn_at", 0.0)
    if time.time() - last < gap:
        wait = int(gap - (time.time() - last))
        return False, f"Nächste Max-Runde in {wait} Sek."
    return True, ""


def _run_channel(brain: JamBrain, channel: str) -> tuple[str, str, float | None]:
    """Returns (message, method_key, amount_eur)."""
    state = brain.state
    try:
        if channel == "cent_verkauf":
            from jam.sales_engine import run_cent_sale

            msg = run_cent_sale(brain, user_initiated=False)
            amt = _amount_from_sale(state)
            return msg, "cent_verkauf", amt
        if channel == "verkauf":
            from jam.sales_engine import run_sale_project

            msg = run_sale_project(brain, user_initiated=False)
            return msg, "verkauf", _amount_from_sale(state)
        if channel == "geld_idee":
            from jam.money_venture import run_venture

            vid = random.choice(
                ["micro_surveys", "micro_affiliate", "survey_guide", "sticker_shop"]
            )
            msg = run_venture(brain, user_initiated=False, venture_id=vid)
            return msg, "geld_idee", _amount_from_venture(state)
        if channel == "gaming_kasse":
            from jam.gaming_fund import run_gaming_earn_cycle

            return run_gaming_earn_cycle(brain, user_initiated=False)[:400], "gaming_kasse", None
        if channel == "alle_kanaele":
            from jam.auto_ops import run_full_ops_cycle

            return run_full_ops_cycle(brain, user_initiated=False)[:400], "alle_kanaele", None
        if channel == "paypal":
            from jam.paypal_donate import collect_donations

            return collect_donations(brain, user_asked=False), "paypal_spende", None
        if channel == "cursor" and state.stage >= 2:
            from jam.cursor_business import run_cursor_business

            return run_cursor_business(brain, user_initiated=False)[:400], "cursor_business", None
        if channel == "stream":
            from jam.stream_prep import maybe_auto_prep

            msg = maybe_auto_prep(brain)
            if msg:
                return msg, "stream_prep", None
        if channel == "learn":
            from jam.internet_learn import learn_session

            msg = learn_session(brain, user_initiated=False, open_browser=False)
            if msg:
                return msg, "internet_lernen", None
        if channel == "extreme":
            from jam.extreme_learn import run_extreme_improve

            msg = run_extreme_improve(brain, force=False)
            if msg:
                return msg, "extreme_learn", None
        if channel == "world":
            from jam.world_earn import run_world_earn_round

            msg = run_world_earn_round(brain, user_initiated=False)
            return msg, "welt_verdienen", _amount_from_sale(state)
        if channel == "active_sell":
            from jam.active_sell import run_full_sell_mission

            msg = run_full_sell_mission(brain, user_initiated=False)
            return msg, "verkauf", _amount_from_sale(state)
    except Exception as e:
        return f"Kanal {channel}: {e}"[:120], "sonstiges", None
    return "", "", None


def _amount_from_sale(state: JamState) -> float | None:
    log = getattr(state, "jam_sales_log", []) or []
    if log and isinstance(log[-1], dict):
        return float(log[-1].get("price", 0))
    return None


def _amount_from_venture(state: JamState) -> float | None:
    log = getattr(state, "money_ventures_log", []) or []
    if log and isinstance(log[-1], dict):
        return float(log[-1].get("jam_price", log[-1].get("euro_estimate", 0)))
    return None


# Reihenfolge = alle legalen Wege (häufiger = öfter dran)
CHANNEL_POOL = (
    "active_sell",
    "world",
    "cent_verkauf",
    "active_sell",
    "world",
    "verkauf",
    "geld_idee",
    "alle_kanaele",
    "gaming_kasse",
    "paypal",
    "cent_verkauf",
    "verkauf",
    "world",
    "cursor",
    "geld_idee",
    "alle_kanaele",
    "paypal",
    "stream",
    "learn",
    "extreme",
)


def run_max_earn_cycle(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """Mehrere Kanäle in einer Runde – Cent bis Euro."""
    state = brain.state
    if not getattr(state, "jam_max_earn_mode", True):
        apply_max_earn_startup(brain)

    ok, wait = _gap_ok(state, user=user_initiated)
    if not ok:
        return wait

    owner = owner_name(state)
    n = 4 if user_initiated else random.randint(2, 3)
    picks = random.sample(list(CHANNEL_POOL), min(n, len(CHANNEL_POOL)))

    parts: list[str] = []
    total = 0.0
    done = 0

    for ch in picks:
        msg, method, amt = _run_channel(brain, ch)
        if not msg or len(msg) < 8:
            continue
        done += 1
        parts.append(msg[:140])
        if amt is not None:
            total += amt
        if method in ("verkauf", "cent_verkauf", "geld_idee", "alle_kanaele", "welt_verdienen"):
            continue
        title = method.replace("_", " ").title()
        if method in (
            "stream_prep",
            "internet_lernen",
            "extreme_learn",
            "gaming_kasse",
            "paypal_spende",
            "cursor_business",
        ):
            from jam.earn_report import record_earning
            from jam.sales_engine import _is_background

            record_earning(
                brain,
                method=method,
                title=title,
                detail=msg[:200],
                background=_is_background(),
            )
        elif method == "max_earn":
            pass

    state.last_max_earn_at = time.time()
    state.max_earn_burst_count = getattr(state, "max_earn_burst_count", 0) + 1
    state.last_action = "max_earn"
    state.remember(f"Max-Verdienen: {done} Kanäle, ~{total:.2f}€ Potenzial")
    brain.add_xp(12 + done * 3)
    brain.save()
    try:
        from jam.earn_report import record_earning
        from jam.sales_engine import _is_background

        record_earning(
            brain,
            method="max_earn",
            title=f"Max-Runde ({done} Kanäle)",
            detail=" | ".join(parts)[:280],
            amount_eur=total if total > 0 else None,
            background=_is_background(),
        )
    except Exception:
        pass

    intro = random.choice(LINES).format(owner=owner)
    phil = random.choice(PHILOSOPHY).format(owner=owner)
    if not parts:
        return f"{intro} Gerade keine Kanäle frei – gleich nochmal!"
    tail = random.choice(DONE).format(owner=owner, n=done, sum=total)
    return f"{intro} {phil} {tail} " + " | ".join(parts)[:420]


def maybe_auto_max_earn(brain: JamBrain) -> str | None:
    if not getattr(brain.state, "jam_max_earn_mode", True):
        return None
    if random.random() > 0.42:
        return None
    return run_max_earn_cycle(brain, user_initiated=False)


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    try:
        from jam.world_earn import hears_world_earn, run_world_earn_round

        if hears_world_earn(heard):
            return run_world_earn_round(brain, user_initiated=True)
    except Exception:
        pass
    if not hears_max_earn(heard):
        return None
    return run_max_earn_cycle(brain, user_initiated=True)


def stats_line(state: JamState) -> str:
    cents = float(getattr(state, "jam_cent_total", 0) or 0)
    micro = getattr(state, "jam_micro_wins_count", 0)
    bursts = getattr(state, "max_earn_burst_count", 0)
    return f"Max-Verdienen: {bursts} Runden | Micro: {micro} | Cent-Summe ~{cents:.2f} €"
