"""
Geld-Sprint bis Stichtag (z. B. 6.6.2026): Spenden + Verkauf mit höchster Priorität.

Ehrlich: Jam kann Chancen maximieren – echtes Geld nur durch Käufer/Spender.
"""

from __future__ import annotations

import random
import time
from datetime import datetime

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

DEADLINE_ROOT = __import__("pathlib").Path.home() / "Documents" / "Jam-Deadline-0606"
DEFAULT_DEADLINE = datetime(2026, 6, 6, 23, 59, 59)
SPRINT_GAP_SEC = 48.0
USER_GAP_SEC = 22.0

LINES = (
    "{owner}, **Sprint bis {date}** ist AN! Ich pushe **Spenden + Verkauf** – "
    "PayPal {paypal}. Echtes Geld = wenn jemand zahlt!",
    "Bis {date} gebe ich Vollgas: Produkte, Fiverr, Spenden, dringende Angebote – du musst wenig tun!",
    "{owner}, noch **{days} Tag(e)** – ich mache alles für Spenden & Verkauf. "
    "Einmal Jam-Edge einloggen hilft am meisten!",
)


def deadline_ts(state: JamState) -> float:
    until = float(getattr(state, "jam_deadline_until", 0) or 0)
    if until > 0:
        return until
    return DEFAULT_DEADLINE.timestamp()


def deadline_label(state: JamState) -> str:
    return getattr(state, "jam_deadline_label", "") or "6.6.2026"


def is_deadline_sprint(state: JamState) -> bool:
    if not getattr(state, "jam_deadline_mode", False):
        return False
    if time.time() > deadline_ts(state):
        return False
    return True


def days_left(state: JamState) -> int:
    left = deadline_ts(state) - time.time()
    return max(0, int(left / 86400) + (1 if left % 86400 else 0))


def hears_deadline_goal(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(
        p in h
        for p in (
            "6.6.26",
            "6.6.2026",
            "06.06",
            "6.6.",
            "6 juni",
            "6. juni",
            "sechsten juni",
            "bis 6.6",
            "bis 6 6",
            "bis zum 6",
        )
    ):
        if any(w in h for w in ("geld", "verdien", "spend", "verkauf", "brauch", "viel", "reich")):
            return True
    if "viel geld" in h or "viel geld brauch" in h:
        if any(w in h for w in ("bis", "6", "juni", "deadline", "dringend")):
            return True
    if "brauche" in h and "geld" in h and any(w in h for w in ("bis", "6", "juni", "schnell")):
        return True
    return False


def _write_sprint_note(owner: str, days: int) -> __import__("pathlib").Path:
    DEADLINE_ROOT.mkdir(parents=True, exist_ok=True)
    path = DEADLINE_ROOT / "DAVID_BIS_0606.txt"
    path.write_text(
        f"""JAM – GELD-SPRINT BIS 6.6.2026 ({owner})
==========================================
{datetime.now().strftime('%d.%m.%Y %H:%M')}
Noch ca. {days} Tag(e) bis Stichtag.

EHRLICH:
- Jam kann NICHT garantieren wie viel € auf PayPal landen.
- Echtes Geld = Spende (PayPal) ODER Kauf (Fiverr/Gumroad/PayPal-Kauf).
- In 2–3 Tagen sind oft erste **Cent–Euro** möglich – wenn du Links teilst & Gigs LIVE sind.

JAM MACHT AUTOMATISCH:
✓ Produkte bauen & verkaufen (auch Cent-Preise)
✓ PayPal-Spenden bewerben
✓ Fiverr/Gumroad/Freelancer pushen
✓ Dringende Programmier-Angebote
✓ Kunden ansprechen (wenn Freigabe AN)

DU – 15 MINUTEN (größter Hebel):
1. Jam-Edge öffnen → Gmail, Fiverr, Gumroad einloggen
2. Letztes Fiverr-Gig + Gumroad **veröffentlichen** (Texte liegen fertig)
3. PayPal-Link + Shop-Link an 3–5 Freunde / Telegram / Discord

PayPal: {PAYPAL_EMAIL}

Sag zu Jam: „Jam, Geld Status“ oder „Sprint Status“
""",
        encoding="utf-8",
    )
    return path


def enable_deadline_sprint(
    brain: JamBrain,
    *,
    heard: str = "",
    deadline: datetime | None = None,
    run_blitz: bool = True,
) -> str:
    """Volle Verdienst-Power bis Stichtag."""
    from jam.money_all_in import enable_money_all_in
    from jam.night_focus import enable_night_sell_donate

    state = brain.state
    owner = owner_name(state)
    end = deadline or DEFAULT_DEADLINE
    state.jam_deadline_mode = True
    state.jam_deadline_until = end.timestamp()
    state.jam_deadline_label = end.strftime("%d.%m.%Y")
    state.jam_deadline_since = time.time()

    enable_money_all_in(brain, heard=heard or "sprint bis 6.6", run_blitz=run_blitz)
    try:
        from jam.jam_browser_auto import enable_browser_autopilot

        enable_browser_autopilot(brain)
    except Exception:
        state.jam_browser_autopilot = True
    enable_night_sell_donate(brain, intensity=0.9, with_learn=True)
    state.jam_night_focus_until = end.timestamp()
    state.jam_night_intensity = 0.9

    note = _write_sprint_note(owner, days_left(state))
    state.last_action = "deadline_sprint"
    state.remember(f"Geld-Sprint bis {deadline_label(state)}")
    brain.add_xp(15)
    brain.save()

    try:
        import os
        import subprocess

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

    d = days_left(state)
    return (
        random.choice(LINES).format(
            owner=owner,
            date=deadline_label(state),
            days=d,
            paypal=PAYPAL_EMAIL,
        )
        + f" Plan: {note.name}. Hintergrund läuft schneller!"
    )[:720]


def can_sprint(state: JamState, *, user: bool = False) -> tuple[bool, str]:
    if not is_deadline_sprint(state):
        return False, "Sprint vorbei oder aus."
    gap = USER_GAP_SEC if user else SPRINT_GAP_SEC
    if time.time() - getattr(state, "last_deadline_sprint_at", 0.0) < gap:
        wait = int(gap - (time.time() - state.last_deadline_sprint_at))
        return False, f"Nächster Sprint-Schritt in {wait} Sek."
    return True, ""


def run_deadline_sprint_step(brain: JamBrain, *, user_initiated: bool = False) -> str:
    """Eine Aktion: Spende, Verkauf, Push oder dringendes Angebot."""
    state = brain.state
    if not is_deadline_sprint(state):
        return enable_deadline_sprint(brain)

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

    owner = owner_name(state)
    pick = random.choices(
        ["donate", "sell", "cent", "push", "urgent", "contact"],
        weights=[22, 22, 18, 18, 12, 8],
        k=1,
    )[0]
    detail = ""

    try:
        if pick == "donate":
            from jam.paypal_donate import collect_donations

            detail = collect_donations(brain, user_asked=user_initiated)
        elif pick == "cent":
            from jam.sales_engine import run_cent_sale

            detail = run_cent_sale(brain, user_initiated=user_initiated)
        elif pick == "sell":
            from jam.sales_engine import run_sale_project

            detail = run_sale_project(brain, user_initiated=user_initiated)
        elif pick == "push":
            from jam.active_sell import maybe_active_sell_push, run_sell_after_login

            if getattr(state, "jam_platforms_logged_in", False):
                detail = run_sell_after_login(brain)[:400]
            else:
                detail = maybe_active_sell_push(brain) or "Verkaufs-Push: Login in Jam-Edge hilft!"
        elif pick == "urgent":
            from jam.urgent_offers import create_urgent_offer

            detail = create_urgent_offer(brain, user_initiated=user_initiated)
        else:
            from jam.outbound_sales import create_outbound_prospect

            detail = create_outbound_prospect(brain, user_initiated=user_initiated)
    except Exception as e:
        detail = f"Sprint-Fehler: {e}"[:120]

    state.last_deadline_sprint_at = time.time()
    state.deadline_sprint_count = getattr(state, "deadline_sprint_count", 0) + 1
    state.last_action = "deadline_sprint"
    brain.add_xp(6 if user_initiated else 3)
    brain.save()

    days = days_left(state)
    return (
        f"⚡ Sprint ({deadline_label(state)}, noch ~{days}d): {detail}"[:520]
    )


def maybe_deadline_sprint(brain: JamBrain) -> str | None:
    if not is_deadline_sprint(brain.state):
        return None
    if random.random() > 0.58:
        return None
    ok, _ = can_sprint(brain.state, user=False)
    if not ok:
        return None
    return run_deadline_sprint_step(brain, user_initiated=False)


def status_line(state: JamState) -> str:
    if not getattr(state, "jam_deadline_mode", False):
        return ""
    if not is_deadline_sprint(state):
        return "Geld-Sprint: Stichtag erreicht – weiter verkaufen möglich."
    n = getattr(state, "deadline_sprint_count", 0)
    return (
        f"Sprint bis {deadline_label(state)} · ~{days_left(state)}d · "
        f"{n} Schritte · PayPal {PAYPAL_EMAIL}"
    )


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    h = heard.lower()
    if "sprint status" in h or ("geld" in h and "status" in h and "6" in h):
        return status_line(brain.state) or enable_deadline_sprint(brain, heard=heard)
    if hears_deadline_goal(heard):
        return enable_deadline_sprint(brain, heard=heard)
    return None
