"""
Jam-Tempo: 100 % = normal, 50 % = halb so schnell (längere Pausen, ruhiger Desktop).
"""

from __future__ import annotations

from jam.brain import JamBrain, JamState


def pace_percent(state: JamState) -> int:
    return max(25, min(150, int(getattr(state, "jam_pace_percent", 100) or 100)))


def pace_multiplier(state: JamState) -> float:
    """50 % Tempo → Faktor 2.0 (doppelte Wartezeit)."""
    return 100.0 / pace_percent(state)


def gap_seconds(state: JamState, base_sec: float) -> float:
    return base_sec * pace_multiplier(state)


def move_interval_ms(state: JamState, base_ms: int = 16) -> int:
    return max(20, int(base_ms * pace_multiplier(state)))


def apply_pace(brain: JamBrain, percent: int) -> str:
    brain.state.jam_pace_percent = max(25, min(150, int(percent)))
    brain.state.remember(f"Jam-Tempo: {brain.state.jam_pace_percent} %")
    brain.save()
    return (
        f"Jam läuft jetzt mit **{brain.state.jam_pace_percent} % Tempo** "
        f"(Pause ×{pace_multiplier(brain.state):.1f})."
    )


def apply_sell_focus_slow(brain: JamBrain, *, pace: int = 50) -> str:
    """Fokus: nur verkaufen + Werbung, keine neuen Produkte."""
    from jam.sell_focus import apply_sell_without_build

    apply_pace(brain, pace)
    return apply_sell_without_build(brain, pace=None)


def hears_pace_or_sell_focus(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("50", "halb")) and any(w in h for w in ("langsam", "tempo", "prozent", "%")):
        return True
    if any(w in h for w in ("verkauf", "werbung", "verkaufen")):
        if any(w in h for w in ("fokus", "mehr", "eher", "nur", "langsam")):
            return True
    if "start" in h and any(w in h for w in ("verkauf", "werbung", "langsam")):
        return True
    return False


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if not hears_pace_or_sell_focus(heard):
        return None
    h = heard.lower()
    pct = 50
    m = __import__("re").search(r"(\d{2,3})\s*(?:%|prozent)", h)
    if m:
        pct = int(m.group(1))
    if any(w in h for w in ("verkauf", "werbung", "verkaufen", "fokus")):
        return apply_sell_focus_slow(brain, pace=pct)
    return apply_pace(brain, pct)
