"""Jam lernt sich extrem zu verbessern – Crashes, Logs, Internet, Cursor."""

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.upbringing import ensure_traits

IMPROVE_ROOT = Path.home() / "Documents" / "Jam-Extrem-Lernen"
CRASH_LOG = Path(__file__).resolve().parent.parent / "data" / "jam-crash.log"
EARN_LOG = Path(__file__).resolve().parent.parent / "data" / "jam-earn.log"
GAP_SEC = 180.0

TOPICS = (
    "geld verdienen online verbessern",
    "verkauf digital produkte optimieren",
    "paypal business tipps",
    "KI assistent lernen deutsch",
    "freelance schneller verdienen",
    "automation python geld",
)

LINES = (
    "{owner}, ich lerne mich **extrem** weiter – besser verdienen für dich!",
    "Extrem-Lern-Modus: Ich werde schlauer bei Geld & Code!",
)


def hears_extreme_learn(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if "extrem" in h and any(w in h for w in ("lern", "verbesser", "besser")):
        return True
    if "verbesser dich extrem" in h or "lern dich verbesser" in h:
        return True
    return False


def _read_tail(path: Path, n: int = 1200) -> str:
    try:
        if path.is_file():
            return path.read_text(encoding="utf-8", errors="replace")[-n:]
    except OSError:
        pass
    return ""


def _lesson_from_crash() -> str:
    tail = _read_tail(CRASH_LOG)
    if "Traceback" in tail or "Error" in tail or "Fehler" in tail:
        lines = [ln for ln in tail.splitlines() if ln.strip()][-8:]
        return "Crash-Fix lernen: " + " | ".join(lines)[-300:]
    return "Kein Crash – ich bleibe stabil laufen."


def _lesson_from_earn() -> str:
    tail = _read_tail(EARN_LOG, 800)
    if tail:
        return "Aus Erfolg lernen: " + tail.splitlines()[-1][:200]
    return "Noch keine Hintergrund-Logs."


def can_run(state: JamState) -> bool:
    if time.time() - getattr(state, "last_extreme_learn_at", 0.0) < GAP_SEC:
        return False
    return True


def run_extreme_improve(brain: JamBrain, *, force: bool = False) -> str:
    state = brain.state
    if not force and not can_run(state):
        return ""

    owner = owner_name(state)
    ensure_traits(state)
    lessons: list[str] = []

    lessons.append(_lesson_from_crash())
    lessons.append(_lesson_from_earn())

    topic = random.choice(TOPICS)
    try:
        from jam.internet_learn import fetch_from_internet

        label, sentences, _url = fetch_from_internet(topic)
        if sentences:
            lessons.append(f"{label}: {sentences[0][:180]}")
            for s in sentences[:2]:
                state.learn_word(s.split()[0][:12] if s.split() else topic)
    except Exception as e:
        lessons.append(f"Online: {topic} ({e})")

    try:
        from jam import sentence_learn

        sentence_learn.remember_sentences(
            state,
            [
                f"Ich verbessere mich extrem für {owner}.",
                "Mein nächster Verkauf wird besser.",
                "Ich lerne aus Fehlern und werde stärker.",
            ],
        )
    except Exception:
        pass

    state.traits["neugierig"] = min(1.0, state.traits.get("neugierig", 0.5) + 0.06)
    state.traits["hilfsbereit"] = min(1.0, state.traits.get("hilfsbereit", 0.5) + 0.05)
    state.traits["süß"] = min(1.0, state.traits.get("süß", 0.5) + 0.03)
    state.discipline = min(1.0, state.discipline + 0.04)

    cursor_msg = ""
    try:
        from jam import cursor_lab

        if cursor_lab.cursor_available() and state.stage >= 2:
            ok, cursor_msg, _ = cursor_lab.create_self_improve_session(brain)
            if ok:
                lessons.append("Cursor: Selbst-Verbesserung gestartet.")
    except Exception:
        pass

    IMPROVE_ROOT.mkdir(parents=True, exist_ok=True)
    stamp = datetime.now().strftime("%Y%m%d-%H%M")
    path = IMPROVE_ROOT / f"VERBESSERUNG-{stamp}.md"
    body = (
        f"# Jam Extrem-Lernen\n\n"
        f"Für: {owner}\n"
        f"Zeit: {datetime.now().strftime('%d.%m.%Y %H:%M')}\n\n"
        "## Lektionen\n\n"
        + "\n".join(f"- {l}" for l in lessons)
        + "\n\n## Ziel\n"
        "Immer besser Geld verdienen, weniger abstürzen, smarter für David.\n"
    )
    path.write_text(body, encoding="utf-8")
    (IMPROVE_ROOT / "LETZTE_VERBESSERUNG.md").write_text(body, encoding="utf-8")

    log = list(getattr(state, "extreme_learn_log", []) or [])
    log.append({"at": time.time(), "topic": topic, "file": str(path)})
    state.extreme_learn_log = log[-30:]
    state.extreme_learn_count = getattr(state, "extreme_learn_count", 0) + 1
    state.last_extreme_learn_at = time.time()
    state.last_action = "extreme_learn"
    state.remember(f"Extrem-Lernen: {topic}")
    brain.add_xp(22)
    brain.save()

    intro = random.choice(LINES).format(owner=owner)
    return f"{intro} {cursor_msg} Notiz: {path.name}"


def maybe_auto_extreme(brain: JamBrain) -> str | None:
    state = brain.state
    if state.stage < 1:
        return None
    if random.random() > 0.22:
        return None
    msg = run_extreme_improve(brain, force=False)
    return msg or None


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_extreme_learn(heard):
        return None
    return run_extreme_improve(brain, force=True) or "Ich lerne gerade extrem weiter!"


def stats_line(state: JamState) -> str:
    return f"Extrem-Lernen: {getattr(state, 'extreme_learn_count', 0)} Sessions"
