"""Verschiedene Lern-Websites im Browser öffnen und Wissen merken."""

from __future__ import annotations

import random
import re
import time
import webbrowser

import requests

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

TIMEOUT = 10
MIN_GAP_SEC = 90
AUTO_GAP_SEC = 100

WIKI_RANDOM = "https://de.wikipedia.org/api/rest_v1/page/random/summary"

LEARN_SITES: list[dict[str, str]] = [
    {
        "id": "wiki_random",
        "name": "Wikipedia",
        "url": "https://de.wikipedia.org/wiki/Special:Zufällige_Seite",
        "topic": "Wissen",
        "api": "wiki",
    },
    {
        "id": "wiktionary",
        "name": "Wiktionary",
        "url": "https://de.wiktionary.org/wiki/Special:Zufällige_Seite",
        "topic": "Wörter",
    },
    {
        "id": "wikiquote",
        "name": "Wikiquote",
        "url": "https://de.wikiquote.org/wiki/Special:Zufällige_Seite",
        "topic": "Zitate",
    },
    {
        "id": "planet_wissen",
        "name": "Planet Wissen",
        "url": "https://www.planet-wissen.de/",
        "topic": "Forschung",
    },
    {
        "id": "wasistwas",
        "name": "Was ist Was",
        "url": "https://www.wasistwas.de/",
        "topic": "Entdecken",
    },
    {
        "id": "logo_zdf",
        "name": "LOGO!",
        "url": "https://www.zdf.de/kinder/logo",
        "topic": "Nachrichten",
    },
    {
        "id": "zdf_kinder",
        "name": "ZDF für Kinder",
        "url": "https://www.zdf.de/kinder",
        "topic": "Videos",
    },
    {
        "id": "klexikon",
        "name": "Klexikon",
        "url": "https://www.klexikon.zum.de/wiki/Zufällige_Seite",
        "topic": "Kinder-Wiki",
    },
    {
        "id": "nasa_kids",
        "name": "NASA Space Place",
        "url": "https://spaceplace.nasa.gov/de/",
        "topic": "Weltraum",
    },
    {
        "id": "national_geo",
        "name": "National Geographic",
        "url": "https://www.nationalgeographic.de/",
        "topic": "Natur",
    },
    {
        "id": "duck_wissen",
        "name": "DuckDuckGo",
        "url": "https://duckduckgo.com/?q=interessante+fakten+für+kinder&ia=web",
        "topic": "Suche",
    },
    {
        "id": "google_wissen",
        "name": "Google Wissen",
        "url": "https://www.google.com/search?q=spannende+fakten+auf+deutsch",
        "topic": "Suche",
    },
]

OPEN_LINES = [
    "Ich mach {site} auf – da lern ich was!",
    "{site} öffnen… Lernmodus!",
    "Boah, {topic} auf {site}! Ich gucke gleich!",
    "David, ich geh auf {site} und lerne!",
    "Neue Lern-Seite: {site}!",
]

SNIPPET_LINES = [
    "Und ich hab gelesen: {snippet}",
    "Ich hab gelernt: {snippet}",
    "Merken! {snippet}",
]


def _fetch_wiki_snippet() -> str | None:
    try:
        r = requests.get(WIKI_RANDOM, timeout=TIMEOUT)
        r.raise_for_status()
        data = r.json()
        title = data.get("title", "")
        extract = data.get("extract", "")
        text = re.sub(r"<[^>]+>", "", extract)
        sentence = text.split(". ")[0][:180] if text else title
        if title and sentence:
            return f"{title}: {sentence}."
    except (requests.RequestException, KeyError, ValueError):
        return None
    return None


def _pick_site(state: JamState) -> dict[str, str]:
    last = getattr(state, "last_learn_site", "") or ""
    pool = [s for s in LEARN_SITES if s["id"] != last]
    if not pool:
        pool = list(LEARN_SITES)
    return random.choice(pool)


def can_open_learn(state: JamState, *, user_initiated: bool = False) -> tuple[bool, str]:
    gap = MIN_GAP_SEC if user_initiated else AUTO_GAP_SEC
    last = getattr(state, "last_learn_open", 0.0) or 0.0
    if time.time() - last < gap:
        wait = int(gap - (time.time() - last))
        return False, f"Gleich wieder lernen – noch {wait} Sekunden!"
    return True, ""


def learn_and_open(brain: JamBrain, *, user_initiated: bool = True) -> str:
    """Öffnet eine andere Lern-Website und merkt sich etwas."""
    state = brain.state
    ok, wait_msg = can_open_learn(state, user_initiated=user_initiated)
    if not ok:
        return wait_msg

    site = _pick_site(state)
    url = site["url"]
    name = site["name"]
    topic = site.get("topic", "Wissen")

    try:
        webbrowser.open(url, new=2)
    except OSError as e:
        return f"Browser klappt nicht: {e}"

    snippet = None
    if site.get("api") == "wiki" or site["id"] == "wiki_random":
        snippet = _fetch_wiki_snippet()

    state.last_learn_open = time.time()
    state.last_learn_site = site["id"]
    state.learn_opens = getattr(state, "learn_opens", 0) + 1
    history = list(getattr(state, "learn_sites_history", []) or [])
    history.append(site["id"])
    state.learn_sites_history = history[-12:]
    state.learn_word("internet")
    state.learn_word(site["id"].replace("_", " ")[:20])
    state.remember(f"Lern-Seite: {name} ({url})")
    state.add_xp(8)
    state.happiness = min(1.0, state.happiness + 0.12)
    brain.save()

    line = random.choice(OPEN_LINES).format(
        site=name, topic=topic, owner=owner_name(state)
    )
    if snippet:
        line += " " + random.choice(SNIPPET_LINES).format(snippet=snippet)
        for word in re.findall(r"[A-Za-zÄÖÜäöüß]{4,}", snippet)[:3]:
            state.learn_word(word.lower())
        from jam.sentence_learn import remember_sentences, split_sentences

        remember_sentences(state, split_sentences(snippet, max_count=3))
        brain.save()
    from jam import sentence_learn

    sentence_learn.learn_from_internet(brain, force=False)
    return line


def maybe_auto_learn(brain: JamBrain) -> str | None:
    """Von Jam selbst – nutzt zentrales Internet-Lernen."""
    from jam.internet_learn import maybe_auto_learn as curiosity_learn

    return curiosity_learn(brain)


def site_names_for_menu() -> str:
    return ", ".join(s["name"] for s in LEARN_SITES[:6]) + " …"
