"""
Alle Jam-Aufgaben stoppen – Hintergrund, Verkauf, Mining, Werbung, Autopilot.
Jam bleibt sichtbar auf dem Desktop; du kannst Aufgaben später wieder starten.
"""

from __future__ import annotations

import os
import subprocess
import time
from pathlib import Path

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

ROOT = Path(__file__).resolve().parent.parent
EARN_PID = ROOT / "data" / "jam-earn.pid"
WATCHDOG_LOCK = ROOT / "data" / "jam-geld-watchdog.lock"

# Modus-Flags → False beim Stopp
_MODE_FLAGS = (
    "jam_delegate_mode",
    "jam_max_earn_mode",
    "jam_active_sell_mode",
    "jam_world_earn_mode",
    "jam_earn_night_mode",
    "jam_shop_heavy_promo",
    "jam_money_all_in_mode",
    "jam_outbound_sales_mode",
    "jam_ad_earn_mode",
    "jam_deadline_mode",
    "jam_auto_email_mode",
    "jam_survey_earn_mode",
    "jam_platform_signup_mode",
    "jam_browser_autopilot",
    "jam_auto_publish",
    "jam_contact_auto",
    "jam_fiverr_focus_mode",
    "jam_shop_always_on",
    "jam_sell_only_mode",
    "jam_sell_focus_mode",
    "jam_no_product_build",
    "gaming_fund_enabled",
    "jam_torchwood_watch",
    "jam_torchwood_chat_read",
    "jam_pc_activity_learn",
    "jam_gpu_mining_on",
    "jam_pc_mining_on",
)

_STOP_LINES = (
    "{owner}, **alle Aufgaben gestoppt**. Jam macht nichts mehr im Hintergrund.",
    "Okay {owner} – Verkauf, Werbung, Mining, Autopilot: **aus**.",
    "Pause! Ich laufe nur noch als Begleiter – sag Bescheid wenn ich wieder starten soll.",
)


def is_all_tasks_stopped(state: JamState) -> bool:
    return bool(getattr(state, "jam_all_tasks_stopped", False))


def _kill_pid(pid: int) -> bool:
    try:
        subprocess.run(
            ["taskkill", "/PID", str(pid), "/F"],
            capture_output=True,
            timeout=12,
            check=False,
        )
        return True
    except (OSError, subprocess.TimeoutExpired):
        return False


def _stop_background_earn_scripts() -> int:
    """Beendet jam_geld_hintergrund / watchdog (wie stop-jam-geld.bat)."""
    killed = 0
    try:
        out = subprocess.run(
            [
                "powershell",
                "-NoProfile",
                "-Command",
                "Get-CimInstance Win32_Process -Filter \"Name='python.exe' OR Name='pythonw.exe'\" "
                "| Where-Object { $_.CommandLine -like '*jam_geld_watchdog*' "
                "-or $_.CommandLine -like '*jam_geld_hintergrund*' } "
                "| Select-Object -ExpandProperty ProcessId",
            ],
            capture_output=True,
            text=True,
            timeout=25,
            check=False,
        )
        for line in (out.stdout or "").splitlines():
            line = line.strip()
            if line.isdigit():
                if _kill_pid(int(line)):
                    killed += 1
    except (OSError, subprocess.TimeoutExpired):
        pass
    if EARN_PID.is_file():
        try:
            pid = int(EARN_PID.read_text(encoding="utf-8").strip())
            if _kill_pid(pid):
                killed += 1
        except (ValueError, OSError):
            pass
        try:
            EARN_PID.unlink(missing_ok=True)
        except OSError:
            pass
    try:
        WATCHDOG_LOCK.unlink(missing_ok=True)
    except OSError:
        pass
    return killed


def stop_all_tasks(brain: JamBrain) -> str:
    """State + Mining + Hintergrund-Prozesse stoppen."""
    state = brain.state
    owner = owner_name(state)

    state.jam_all_tasks_stopped = True
    state.jam_programming_stopped = True
    for key in _MODE_FLAGS:
        setattr(state, key, False)
    state.jam_night_focus = ""
    state.jam_night_focus_until = 0.0
    state.jam_night_intensity = 0.0
    state.jam_platform_signup_until = 0.0
    state.jam_deadline_until = 0.0
    state.last_action = "stop_all_tasks"
    state.remember("Alle Aufgaben gestoppt")
    brain.save()

    extras: list[str] = []
    try:
        from jam.gpu_mining import stop_gpu_mining

        bit = stop_gpu_mining()
        if bit:
            extras.append(bit[:80])
    except Exception as e:
        extras.append(f"GPU: {e}"[:40])
    try:
        from jam.usb_miner_setup import stop_pc_mining

        bit = stop_pc_mining(brain)
        if bit:
            extras.append(bit[:80])
    except Exception as e:
        extras.append(f"Mining: {e}"[:40])
    try:
        from jam.torchwood_moderator import stop_chat_watcher, disable_watch

        extras.append(stop_chat_watcher()[:60])
        extras.append(disable_watch(brain)[:60])
    except Exception:
        pass
    try:
        from jam.shop_heavy_promo import disable_heavy_promo

        disable_heavy_promo(brain)
    except Exception:
        pass

    n = _stop_background_earn_scripts()
    if n:
        extras.append(f"{n} Hintergrund-Prozess(e) beendet")

    import random

    msg = random.choice(_STOP_LINES).format(owner=owner)
    if extras:
        msg += " " + " · ".join(extras)
    return msg[:720]


def resume_tasks(brain: JamBrain) -> str:
    """Standard-Aufgaben wieder erlauben (nicht alles einzeln einschalten)."""
    state = brain.state
    state.jam_all_tasks_stopped = False
    state.jam_programming_stopped = False
    state.jam_max_earn_mode = True
    state.jam_active_sell_mode = True
    state.jam_world_earn_mode = True
    state.jam_earn_night_mode = True
    state.gaming_fund_enabled = True
    state.jam_pc_activity_learn = True
    state.last_action = "resume_tasks"
    state.remember("Aufgaben wieder erlaubt")
    brain.save()
    owner = owner_name(state)
    return (
        f"{owner}, Pause ist **aus**. Verkauf & Hintergrund dürfen wieder laufen – "
        "starte Jam neu oder sag „Verkauf-Fokus“ für einen Modus."
    )[:520]


def hears_stop_all(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("stop", "stopp", "pause", "aus", "beende", "beenden")):
        if any(w in h for w in ("alle", "alles", "aufgaben", "task", "hintergrund", "autopilot")):
            return True
    if "keine aufgaben" in h or "nichts mehr machen" in h:
        return True
    if h.strip() in ("stop", "stopp", "pause") and "jam" in text.lower():
        return True
    return False


def hears_resume_tasks(text: str) -> bool:
    h = text.lower().replace("jam", " ")
    if any(w in h for w in ("weiter", "fortsetz", "resume", "wieder an")):
        if any(w in h for w in ("aufgaben", "arbeit", "verkauf", "hintergrund")):
            return True
    return False


def handle_speech(brain: JamBrain, heard: str) -> str | None:
    if hears_resume_tasks(heard):
        return resume_tasks(brain)
    if hears_stop_all(heard):
        return stop_all_tasks(brain)
    return None
