"""Einfaches Internet-Lernen (Deutsch-Wörter, Fakten)."""

from __future__ import annotations

import random

from jam.brain import JamBrain
from jam import web_learn

FALLBACK_WORDS = [
    "Kartoffel", "Sternschnuppe", "Keksmonster", "Flausch", "Zappel",
    "Murmel", "Purpur", "Quatsch", "Knuddel", "Wusel",
]


def fetch_german_snippet() -> str | None:
    return web_learn._fetch_wiki_snippet()


def teach_snippet_only(brain: JamBrain) -> str | None:
    """Nur Fakt merken – kein Browser (z. B. nach dem Füttern)."""
    from jam import sentence_learn

    n, first = sentence_learn.learn_from_internet(brain, force=True)
    if n and first:
        return f"Ich hab {n} Sätze gelernt! Z. B.: {first[:100]}"
    snippet = fetch_german_snippet()
    if snippet:
        from jam.sentence_learn import remember_sentences, split_sentences

        remember_sentences(brain.state, split_sentences(snippet, max_count=4))
        brain.state.remember(snippet)
        brain.state.add_xp(3)
        brain.save()
        return f"Ich hab gelesen: {snippet}"
    word = random.choice(FALLBACK_WORDS)
    brain.state.learn_word(word)
    brain.save()
    return f"Neues Wort: {word}!"


def teach_from_web(brain: JamBrain, *, user_initiated: bool = True) -> str | None:
    """Jam lernt online nach eigenem Thema."""
    from jam.internet_learn import learn_session

    try:
        return learn_session(brain, user_initiated=user_initiated, open_browser=True)
    except Exception:
        word = random.choice(FALLBACK_WORDS)
        brain.state.learn_word(word)
        brain.save()
        return f"Internet spinnt – aber neues Wort: {word}!"
