"""Jam bleibt immer an – kein Beenden, Watchdog startet neu."""

from __future__ import annotations

import os
import random

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

BLOCK_LINES = (
    "{owner}, ich geh **nie** aus! Jam bleibt für dich da – immer!",
    "Nope! Immer-an-Modus – ich beende mich nicht, {owner}!",
    "Jam bleibt wach – du hast gesagt, ich soll nie ausgehen!",
)

ON_LINES = (
    "{owner}, **Immer-an**! Ich lauf dauernd – auch nach Neustart vom Wächter!",
    "Okay! Jam geht nicht mehr aus. PC wach, ich wach, alles wach!",
)


def is_always_on(state: JamState) -> bool:
    if os.environ.get("JAM_ALWAYS_ON", "").strip().lower() in ("1", "true", "yes"):
        return True
    return bool(getattr(state, "jam_always_on", True))


def should_block_quit(state: JamState) -> bool:
    return is_always_on(state)


def enable_always_on(brain: JamBrain) -> str:
    from jam.keep_awake import enable_night_earn

    state = brain.state
    state.jam_always_on = True
    state.remember("Jam Immer-an – geht nie aus")
    brain.add_xp(5)
    brain.save()
    owner = owner_name(state)
    extra = enable_night_earn(brain, persistent_power=True)
    return f"{random.choice(ON_LINES).format(owner=owner)} {extra}"


def apply_always_on_startup(brain: JamBrain) -> None:
    if os.environ.get("JAM_ALWAYS_ON", "").strip().lower() in ("1", "true", "yes"):
        brain.state.jam_always_on = True
    if is_always_on(brain.state):
        brain.state.jam_always_on = True
        # Nacht-Modus wird in keep_awake.apply_on_startup gesetzt – nicht doppelt
    try:
        from jam.human_voice import apply_human_voice_startup

        apply_human_voice_startup(brain)
    except Exception:
        pass


def hears_always_on(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("nie aus", "nie beenden", "immer an", "immer lauf")):
        return True
    if "nicht ausgehen" in h or "nicht beenden" in h:
        return True
    if "dauernd lauf" in h or "24 stunden" in h and "jam" in h:
        return True
    return False


def hears_allow_quit(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    return any(
        x in h
        for x in (
            "darf ausgehen",
            "darf beenden",
            "immer an aus",
            "jam beenden",
            "jam aus machen",
        )
    )


def disable_always_on(brain: JamBrain) -> str:
    state = brain.state
    state.jam_always_on = False
    brain.save()
    return (
        f"{owner_name(state)}, okay – du kannst mich wieder beenden. "
        "Sag „Beenden“ im Menü."
    )


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_allow_quit(heard):
        return disable_always_on(brain)
    if hears_always_on(heard):
        return enable_always_on(brain)
    return None


def block_quit_line(state: JamState) -> str:
    return random.choice(BLOCK_LINES).format(owner=owner_name(state))
