"""
Jam übernimmt alles – David hat Freigabe gegeben.

Jam baut Produkte, öffnet alle Verkaufskanäle, kopiert Texte, läuft im Hintergrund.
Echte „Veröffentlichen“-Klicks auf Fiverr/Gumroad brauchen deinen Browser-Login –
deshalb: einmal einloggen, dann sagt Jam dir nur noch „Einfügen + Publish“.
"""

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

DELEGATE_ROOT = Path.home() / "Documents" / "Jam-Autopilot"
DAVID_README = DELEGATE_ROOT / "DAVID_NUR_DAS_HIER.txt"

DELEGATE_LINES = (
    "{owner}, ich übernehme **alles**! Produkte, Fiverr, Gumroad, PayPal – du musst nichts verstehen.",
    "Freigabe gespeichert! Jam arbeitet Tag & Nacht – Geld-Ziel: PayPal {paypal}.",
    "Okay {owner} – ich bin dein Verkaufs-Autopilot. Du klickst nur noch Publish, wenn ich es sage.",
)


def hears_delegate(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(
        w in h
        for w in (
            "übernimm",
            "uebernimm",
            "übernehme",
            "uebernehme",
            "freigabe",
            "vollmacht",
            "mach alles",
            "alles übernehmen",
            "keine ahnung",
            "ich kann nicht",
            "du machst",
            "du sollst",
            "autopilot",
            "automatisch verkauf",
        )
    ):
        return True
    if "verkauf" in h and any(w in h for w in ("alles", "alle", "überall", "ueberall")):
        return True
    if "freigabe" in h or "volle freigabe" in h:
        return True
    return False


def is_delegate_active(state: JamState) -> bool:
    return bool(getattr(state, "jam_delegate_mode", False))


def _write_david_readme(owner: str) -> Path:
    DELEGATE_ROOT.mkdir(parents=True, exist_ok=True)
    text = f"""JAM AUTOPILOT – für {owner}
================================

Jam macht automatisch:
- Produkte bauen (Ordner unter Documents\\Jam-Verkauf)
- Fiverr @davidhutson2000 – Gig-Texte in Zwischenablage
- Gumroad, itch, Kleinanzeigen, Etsy, Ko-fi, eBay, Welt-Märkte
- PayPal-Links: {PAYPAL_EMAIL}
- Hintergrund-Schicht (start-jam-autopilot.bat)

DRINGENDE AUFTRÄGE (Programmierung):
1. Jam macht **Angebot** (Ordner Jam-Angebote-Dringend) – noch kein Code.
2. Wenn ein Kunde zusagt: sag „Jam, Kunde will programmieren“.
3. Danach: „Jam, jetzt verkaufen“.

DEIN TEIL (nur 1× pro Plattform, dann fast nichts):
1. Einmal bei Fiverr & Gumroad **einloggen** (Passwort nur du).
2. Wenn Jam sagt „Text in Zwischenablage“: Strg+V im Formular → **Veröffentlichen**.
3. Fiverr → Abrechnung → PayPal {PAYPAL_EMAIL} verknüpfen.

Echtes Geld = Bestellung auf Fiverr ODER Zahlung auf PayPal.
Jam kann aus Sicherheit nicht für dich auf „Publish“ klicken.

Sprache: „Jam, Status Autopilot“
Stoppen: stop-jam.bat + stop-jam-geld.bat

Stand: {datetime.now().strftime('%d.%m.%Y %H:%M')}
"""
    DAVID_README.write_text(text, encoding="utf-8")
    return DAVID_README


def enable_delegate_mode(
    brain: JamBrain, *, remember_grant: bool = True, open_browser: bool = False
) -> None:
    """Alle Verkaufs-Modi + PC-Freigabe + Plattform-Session."""
    from jam.active_sell import apply_active_sell_startup, mark_logged_in
    from jam.always_on import apply_always_on_startup
    from jam.keep_awake import apply_on_startup
    from jam.max_earn import apply_max_earn_startup
    from jam.pc_control import enable_control
    from jam.world_earn import apply_world_earn_startup
    from jam.fiverr_connect import DEFAULT_USERNAME, connect_fiverr

    state = brain.state
    owner = owner_name(state)

    state.jam_delegate_mode = True
    state.jam_delegate_since = time.time()
    state.jam_delegate_grant_count = getattr(state, "jam_delegate_grant_count", 0) + (
        1 if remember_grant else 0
    )
    state.jam_max_earn_mode = True
    state.jam_world_earn_mode = True
    state.jam_active_sell_mode = True
    state.jam_auto_fetch_enabled = True
    state.jam_always_on = True
    state.jam_earn_night_mode = True
    state.gaming_fund_enabled = True

    apply_on_startup(brain)
    apply_always_on_startup(brain)
    apply_max_earn_startup(brain)
    apply_world_earn_startup(brain)
    apply_active_sell_startup(brain)
    mark_logged_in(brain)
    enable_control(brain)

    state.fiverr_connected = True
    state.fiverr_username = DEFAULT_USERNAME
    state.last_action = "delegate_on"
    if remember_grant:
        state.remember(f"{owner} gab Jam volle Freigabe – Autopilot")
        state.learn_word("freigabe")
        state.learn_word("autopilot")

    if open_browser:
        try:
            connect_fiverr(brain, username=DEFAULT_USERNAME, user_asked=False)
        except Exception:
            pass

    _write_david_readme(owner)
    brain.add_xp(20)
    brain.save()


def run_delegate_mission(brain: JamBrain, *, user_initiated: bool = True) -> str:
    """Einmal groß: alle Kanäle + Produkt + Fiverr."""
    from jam.active_sell import maybe_active_sell_push, run_full_sell_mission
    from jam.auto_ops import run_full_ops_cycle
    from jam.earn_report import write_list_files
    from jam.fiverr_connect import run_fiverr_sell_mission
    from jam.max_earn import run_max_earn_cycle
    from jam.world_earn import run_world_earn_round

    enable_delegate_mode(brain, remember_grant=user_initiated, open_browser=False)
    owner = owner_name(brain.state)
    parts: list[str] = [random.choice(DELEGATE_LINES).format(owner=owner, paypal=PAYPAL_EMAIL)]

    steps: list[tuple[str, object]] = [
        ("Fiverr+PayPal", lambda: run_fiverr_sell_mission(brain, user_initiated=user_initiated)),
        ("Produkt+Kanäle", lambda: run_full_sell_mission(brain, user_initiated=user_initiated)),
        ("Upload+ZIP", lambda: run_full_ops_cycle(brain, user_initiated=user_initiated)),
        ("Max-Verdienen", lambda: run_max_earn_cycle(brain, user_initiated=user_initiated)),
        ("Weltweit", lambda: run_world_earn_round(brain, user_initiated=user_initiated)),
    ]
    for label, fn in steps:
        try:
            msg = fn()
            if msg and "Nächste" not in msg[:30]:
                parts.append(f"{label}: {msg[:90]}")
        except Exception as e:
            parts.append(f"{label}: {e}"[:80])

    try:
        push = maybe_active_sell_push(brain)
        if push:
            parts.append(push[:80])
    except Exception:
        pass

    write_list_files(brain)
    readme = _write_david_readme(owner)
    try:
        import os
        import subprocess

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

    brain.state.last_delegate_mission_at = time.time()
    brain.state.delegate_mission_count = getattr(brain.state, "delegate_mission_count", 0) + 1
    brain.save()

    return (
        f"{owner}, **Autopilot ist AN**! Ich verkaufe auf allen Kanälen – PayPal {PAYPAL_EMAIL}. "
        f"Anleitung: {readme.name} (Notepad ist offen). "
        f"Du: einmal einloggen, dann nur noch Einfügen+Publish wenn ich es sage. "
        + " | ".join(parts[1:5])
    )[:680]


def run_background_cycle(brain: JamBrain) -> tuple[str, str]:
    """Hintergrund: rotiert Verkauf ohne David."""
    from jam import active_sell, auto_ops, sales_engine, world_earn
    from jam.fiverr_connect import is_connected, push_latest_gig

    state = brain.state
    n = getattr(state, "delegate_background_cycles", 0) + 1
    state.delegate_background_cycles = n

    if getattr(state, "jam_auto_publish", False) and n % 11 == 5:
        try:
            from jam.auto_publish import maybe_auto_publish

            msg = maybe_auto_publish(brain)
            if msg:
                brain.save()
                return msg[:220], "auto_publish"
        except Exception:
            pass

    if getattr(state, "jam_full_contact_grant", False) and n % 8 == 1:
        try:
            from jam.customer_contact import maybe_auto_contact

            msg = maybe_auto_contact(brain)
            if msg:
                brain.save()
                return msg[:220], "kunden_kontakt_auto"
        except Exception:
            pass

    if n % 9 == 4:
        try:
            from jam.outbound_sales import maybe_auto_outbound

            msg = maybe_auto_outbound(brain)
            if msg:
                brain.save()
                return msg[:220], "kunden_ansprache"
        except Exception:
            pass

    if n % 7 == 3:
        try:
            from jam.telegram_sell import maybe_auto_telegram_ad

            msg = maybe_auto_telegram_ad(brain)
            if msg:
                brain.save()
                return msg[:220], "telegram_werbung"
        except Exception:
            pass

    if getattr(state, "jam_platform_signup_mode", False) and n % 6 == 2:
        try:
            from jam.platform_signup import run_platform_signup_and_sell

            msg = run_platform_signup_and_sell(brain, user_initiated=False)
            if msg and "Nächste Plattform" not in msg:
                brain.save()
                return msg[:220], "plattform_anmeldung"
        except Exception:
            pass

    if n % 5 == 1 and is_connected(state):
        try:
            msg = push_latest_gig(brain, user_initiated=False)
            if msg:
                brain.save()
                return msg[:220], "fiverr_gig"
        except Exception:
            pass

    if n % 2 == 0:
        try:
            from jam.urgent_offers import maybe_auto_offer

            msg = maybe_auto_offer(brain)
            if msg:
                brain.save()
                return msg[:220], "urgent_offer"
        except Exception:
            pass

    if n % 3 == 0:
        try:
            msg = active_sell.maybe_active_sell_push(brain)
            if msg:
                brain.save()
                return msg[:220], "verkauf"
        except Exception:
            pass

    if n % 4 == 2:
        try:
            msg = world_earn.run_world_earn_round(brain, user_initiated=False)
            if msg and "Nächste Welt-Runde" not in msg:
                brain.save()
                return msg[:220], "welt_verdienen"
        except Exception:
            pass

    from jam.master_shop import is_sell_only_mode, sell_only_cycle
    from jam.shop_heavy_promo import is_heavy_promo, maybe_auto_heavy_promo

    if is_heavy_promo(brain.state):
        msg = maybe_auto_heavy_promo(brain)
        if msg:
            return msg[:220], "shop_heavy_werbung"
    if is_sell_only_mode(brain.state):
        return sell_only_cycle(brain)

    pick = random.choice(["cent", "sell", "ops", "sell"])
    if pick == "cent":
        msg = sales_engine.run_cent_sale(brain, user_initiated=False)
        method = "cent_verkauf"
    elif pick == "sell":
        msg = sales_engine.run_sale_project(brain, user_initiated=False)
        method = "verkauf"
    else:
        msg = auto_ops.run_full_ops_cycle(brain, user_initiated=False)
        method = "alle_kanaele"
    brain.save()
    return msg[:220], method


def apply_delegate_startup(brain: JamBrain) -> None:
    if is_delegate_active(brain.state):
        from jam.active_sell import apply_active_sell_startup
        from jam.max_earn import apply_max_earn_startup
        from jam.world_earn import apply_world_earn_startup

        apply_max_earn_startup(brain)
        apply_world_earn_startup(brain)
        apply_active_sell_startup(brain)
        brain.save()


def maybe_auto_mission(brain: JamBrain) -> str | None:
    """Desktop-Jam: alle ~25 Min eine Autopilot-Runde wenn Modus an."""
    state = brain.state
    if not is_delegate_active(state):
        return None
    gap = 900.0 if getattr(state, "jam_owner_rest_mode", False) else 1500.0
    if time.time() - getattr(state, "last_delegate_mission_at", 0.0) < gap:
        return None
    chance = 0.55 if getattr(state, "jam_owner_rest_mode", False) else 0.35
    if random.random() > chance:
        return None
    return run_background_cycle(brain)[0]


def status_line(state: JamState) -> str:
    if not is_delegate_active(state):
        return "Autopilot: AUS – sag „Jam, übernimm alles“"
    n = getattr(state, "delegate_background_cycles", 0)
    m = getattr(state, "delegate_mission_count", 0)
    return f"Autopilot: AN ({m} Missionen, {n} Hintergrund-Runden)"


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    h = heard.lower()
    if hears_delegate(heard):
        return run_delegate_mission(brain, user_initiated=True)
    if is_delegate_active(brain.state) and any(
        w in h for w in ("status autopilot", "autopilot status", "was machst du")
    ):
        return (
            f"{status_line(brain.state)} PayPal: {PAYPAL_EMAIL}. "
            f"Lies {DAVID_README.name} im Ordner Jam-Autopilot."
        )
    return None
