"""
Alles dran setzen um an Geld zu kommen – alle Jam-Kanäle gleichzeitig AN.

Ehrlich: Jam kann Chancen maximieren, echtes PayPal-Geld nur durch Käufer.
"""

from __future__ import annotations

import random
import time
from datetime import datetime
from pathlib import Path

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

MONEY_ROOT = Path.home() / "Documents" / "Jam-Geld-Alles"
NOTE_FILE = MONEY_ROOT / "JAM_MACHT_ALLES.txt"

LINES = (
    "{owner}, ich setze **ALLES** dran – Verkauf, Fiverr, Gumroad, Welt, Cent, Telegram, "
    "Freelancer, Publish, Hintergrund – PayPal {paypal}!",
    "Volle Geld-Power AN! Ich stoppe nicht – du musst heute nichts tun, {owner}.",
)

BLITZ_CHANNELS: tuple[tuple[str, str], ...] = (
    ("cent", "cent_verkauf"),
    ("sell", "verkauf"),
    ("max", "max_earn"),
    ("world", "welt_verdienen"),
    ("active", "verkauf_push"),
    ("ops", "alle_kanaele"),
    ("venture", "geld_idee"),
    ("fund", "gaming_kasse"),
    ("donate", "paypal_spende"),
    ("fiverr", "fiverr_gig"),
    ("publish", "auto_publish"),
    ("telegram", "telegram_werbung"),
    ("platform", "plattform_anmeldung"),
    ("outbound", "kunden_ansprache"),
    ("contact", "kunden_kontakt_auto"),
    ("adclick", "klick_werbung"),
    ("sprint", "deadline_sprint"),
)


def hears_money_all_in(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(
        w in h
        for w in (
            "alles dran",
            "alles einsetzen",
            "alles tun",
            "alles machen",
            "maximal geld",
            "an geld kommen",
            "geld verdienen",
            "geld machen",
            "reich werden",
            "viel geld",
        )
    ):
        return True
    if "geld" in h and any(w in h for w in ("alles", "dran", "setzen", "schaff", "hol")):
        return True
    if "paypal" in h and any(w in h for w in ("füll", "fuell", "geld", "voll")):
        return True
    return False


def is_money_all_in(state: JamState) -> bool:
    return bool(getattr(state, "jam_money_all_in_mode", False))


def _write_note(owner: str) -> Path:
    MONEY_ROOT.mkdir(parents=True, exist_ok=True)
    text = f"""JAM – ALLES FÜR GELD ({owner})
==============================
{datetime.now().strftime('%d.%m.%Y %H:%M')}

PayPal-Ziel: {PAYPAL_EMAIL}

JAM MACHT AUTOMATISCH:
- Produkte bauen & verkaufen (auch Cent-Beträge)
- Fiverr Gig + Publish-Versuch
- Gumroad Publish-Versuch
- Gumroad, Etsy, Fiverr, Kleinanzeigen, Welt-Märkte
- Telegram-Werbung, Freelancer, **Kunden weltweit ansprechen** (erst bauen nach Zusage)
- PayPal-Links & Spenden-Push
- Hintergrund alle 1–3 Min (start-jam-geld.bat)

EHRLICH:
- 0 € PayPal = noch kein Käufer – normal am Start
- Jam erfindet kein Geld – nur mehr Sichtbarkeit & Angebote
- Echtes Geld = Zahlung auf PayPal oder Fiverr-Bestellung

DU: nichts – optional einmal Login im Jam-Edge-Fenster wenn es fragt.

Status: „Jam, Geld Status“
"""
    NOTE_FILE.write_text(text, encoding="utf-8")
    return NOTE_FILE


def enable_money_all_in(brain: JamBrain, *, heard: str = "", run_blitz: bool = True) -> str:
    """Schaltet jeden Verdienst-Kanal an + startet erste Blitz-Runde."""
    from jam.active_sell import apply_active_sell_startup, mark_logged_in
    from jam.delegate_mode import enable_delegate_mode
    from jam.keep_awake import enable_night_earn
    from jam.max_earn import apply_max_earn_startup
    from jam.night_focus import enable_learn_sell_platforms
    from jam.platform_signup import enable_platform_signup_sell
    from jam.world_earn import apply_world_earn_startup

    owner = owner_name(brain.state)
    state = brain.state

    state.jam_money_all_in_mode = True
    state.jam_money_all_in_since = time.time()
    state.jam_owner_rest_mode = True
    state.jam_owner_rest_since = time.time()
    state.jam_browser_minimal = False
    state.jam_auto_publish = True
    state.gaming_fund_enabled = True

    enable_delegate_mode(brain, remember_grant=True, open_browser=False)
    mark_logged_in(brain)
    enable_night_earn(brain, persistent_power=True)
    try:
        from jam.resource_budget import enable_memory_budget

        enable_memory_budget(brain, pct=0.5)
    except Exception:
        enable_learn_sell_platforms(brain, hours=96.0, intensity=0.65)
    else:
        enable_learn_sell_platforms(brain, hours=96.0, intensity=0.5)
    enable_platform_signup_sell(brain, hours=96.0, intensity=0.5)
    apply_max_earn_startup(brain)
    apply_world_earn_startup(brain)
    apply_active_sell_startup(brain)

    state.fiverr_connected = True
    state.freelancer_connected = True
    state.telegram_shop_ready = True
    state.jam_outbound_sales_mode = True
    state.jam_full_contact_grant = True
    state.jam_contact_auto = True
    try:
        from jam.ad_earn import enable_ad_earn

        enable_ad_earn(brain)
    except Exception:
        state.jam_ad_earn_mode = True

    note = _write_note(owner)
    state.last_action = "money_all_in"
    state.remember("Jam: ALLES für Geld AN")
    brain.add_xp(20)
    brain.save()

    try:
        import os
        import subprocess

        if os.name == "nt":
            subprocess.run(["explorer", str(MONEY_ROOT)], check=False, timeout=5)
    except Exception:
        pass

    blitz = (
        run_money_blitz(brain, user_initiated=True)
        if run_blitz
        else "Erste Blitz-Runde startet im Hintergrund (alle 1–3 Min)."
    )
    return (
        random.choice(LINES).format(owner=owner, paypal=PAYPAL_EMAIL)
        + f" Notiz: {note.name}. {blitz}"
    )[:750]


def run_money_blitz(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """Eine große Runde: viele Kanäle hintereinander."""
    state = brain.state
    owner = owner_name(state)
    parts: list[str] = []
    total = 0.0
    n = 0

    for label, key in BLITZ_CHANNELS:
        try:
            msg, amt = _run_one(brain, key)
            if msg and "Nächste" not in msg[:25]:
                parts.append(f"{label}: {msg[:70]}")
                n += 1
                if amt:
                    total += amt
        except Exception as e:
            parts.append(f"{label}: {e}"[:50])
        if not user_initiated:
            time.sleep(0.3)

    state.money_all_in_blitz_count = getattr(state, "money_all_in_blitz_count", 0) + 1
    state.last_money_blitz_at = time.time()
    brain.save()

    return (
        f"Blitz-Runde #{state.money_all_in_blitz_count}: {n} Kanäle, "
        f"Potenzial ~{total:.2f} €. "
        + " | ".join(parts[:6])
    )[:400]


def _run_one(brain: JamBrain, key: str) -> tuple[str, float | None]:
    if key == "cent_verkauf":
        from jam.sales_engine import run_cent_sale

        return run_cent_sale(brain, user_initiated=False), _amt(brain)
    if key == "verkauf":
        from jam.sales_engine import run_sale_project

        return run_sale_project(brain, user_initiated=False), _amt(brain)
    if key == "max_earn":
        from jam.max_earn import run_max_earn_cycle

        return run_max_earn_cycle(brain, user_initiated=False), None
    if key == "welt_verdienen":
        from jam.world_earn import run_world_earn_round

        return run_world_earn_round(brain, user_initiated=False), None
    if key == "verkauf_push":
        from jam.active_sell import maybe_active_sell_push

        return maybe_active_sell_push(brain) or "", _amt(brain)
    if key == "alle_kanaele":
        from jam.auto_ops import run_full_ops_cycle

        return run_full_ops_cycle(brain, user_initiated=False), None
    if key == "geld_idee":
        from jam.money_venture import run_venture

        return run_venture(brain, user_initiated=False), None
    if key == "gaming_kasse":
        from jam.gaming_fund import run_gaming_earn_cycle

        return run_gaming_earn_cycle(brain, user_initiated=False), None
    if key == "paypal_spende":
        from jam.paypal_donate import collect_donations

        return collect_donations(brain, user_asked=False), None
    if key == "fiverr_gig":
        from jam.fiverr_connect import push_latest_gig

        return push_latest_gig(brain, user_initiated=False) or "", None
    if key == "auto_publish":
        from jam.auto_publish import run_auto_publish_all

        return run_auto_publish_all(brain, user_initiated=False), None
    if key == "telegram_werbung":
        from jam.telegram_sell import run_telegram_ads

        return run_telegram_ads(brain, user_initiated=False), None
    if key == "plattform_anmeldung":
        from jam.platform_signup import run_platform_signup_and_sell

        return run_platform_signup_and_sell(brain, user_initiated=False), None
    if key == "kunden_ansprache":
        from jam.outbound_sales import create_outbound_prospect

        return create_outbound_prospect(brain, user_initiated=False), None
    if key == "kunden_kontakt_auto":
        from jam.customer_contact import run_automated_contact

        return run_automated_contact(brain, user_initiated=False), None
    if key == "klick_werbung":
        from jam.ad_earn import run_ad_earn_cycle

        return run_ad_earn_cycle(brain, user_initiated=False), None
    if key == "deadline_sprint":
        from jam.deadline_earn import run_deadline_sprint_step

        return run_deadline_sprint_step(brain, user_initiated=False), None
    return "", None


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


def maybe_money_blitz(brain: JamBrain) -> str | None:
    if not is_money_all_in(brain.state):
        return None
    if time.time() - getattr(brain.state, "last_money_blitz_at", 0.0) < 420.0:
        return None
    if random.random() > 0.45:
        return None
    return run_money_blitz(brain, user_initiated=False)


def status_line(state: JamState) -> str:
    if not is_money_all_in(state):
        return ""
    n = getattr(state, "money_all_in_blitz_count", 0)
    return f"Geld-Alles-AN: {n} Blitz-Runden | PayPal {PAYPAL_EMAIL}"


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_money_all_in(heard):
        return enable_money_all_in(brain, heard=heard)
    if is_money_all_in(brain.state) and "status" in heard.lower() and "geld" in heard.lower():
        return status_line(brain.state) + f" Verdienst-Liste in Documents."
    return None
