# -*- coding: utf-8 -*-
"""
TeamBot Tray Sidekick (Windows) — v2.5
=======================================
Runs teambot.exe as a HEADLESS server (--server) and provides the tray from
this standalone sidekick process, where pystray pumps in the MAIN thread (the
supported Windows pattern). The frozen exe's internal --tray pump is broken on
this machine (icon registers, messages never dispatch) — do not use it.

v2.3 changelog (2026-11-08, user feedback: the version in the UI
bottom-left corner reads 0 / v0.0.0 on the Windows install):
 12. Version stamp injection: the deployed onefile exe (samai.cc channel,
     <=1.56.16x build) carries NO version source at all — get_version()
     falls through all four probes (TEAMBOT_VERSION env unset, no
     teambot-ai dist-info, package.json NOT bundled into the exe and
     every candidate path points into the per-run _MEI temp dir, no git
     repo) and ends at its last-resort literal "0.0.0". That value flows
     to /api/status r.version -> sidebarVersion (bottom-left), PAGE_BUILD
     and every ?v= cache stamp — hence "all zeros". spawn_server now
     injects TEAMBOT_VERSION=VERSION_STAMP into the child environment;
     core/version.get_version() checks that env var FIRST, so the whole
     chain reports the true deployment version with the CURRENT exe,
     no rebuild needed.
     >>> MAINTENANCE: when the exe is someday rebuilt with a bundled
     >>> package.json (or a frozen-aware core/version.py), UPDATE OR
     >>> REMOVE VERSION_STAMP — the env var outranks the exe's own
     >>> version source and would otherwise mask it. [v2.3]
     Adopted instances (an --server already running when the sidekick
     starts) cannot get the env injected post-hoc; they keep reporting
     0.0.0 until the sidekick-spawned instance replaces them.

v2.5 changelog (2026-11-10, user feedback on the FIRST Inno Setup build
(teambot-setup-1.56.171.exe): "clicking launch only starts the tray, no
service; tray Start Service also does nothing; the desktop icon is not
the real logo"):
 18. APP_DIR is no longer hardcoded to C:\\teambot. The Inno Setup installer
     deploys to {autopf}\\teambot (Program Files or LocalAppData\\Programs),
     but this script still pointed EXE/cwd at C:\\teambot — so on every
     installer machine spawn_server raised FileNotFoundError and NOTHING
     ever started (bug: "launch only starts the tray" + dead Start
     Service menu item). APP_DIR is now the directory THIS .py file lives
     in (dirname(__file__)), which is simultaneously correct for the
     installed layout, the legacy manual C:\\teambot deployment (the script
     lives there too) and any future portable copy. The frozen guard
     (sys.frozen) is kept for symmetry in case the tray is ever frozen.
 19. Mutable sidekick state moved OUT of the install directory: the log
     (teambot_tray.log) and the user-stop latch (sidekick_stop_latch)
     now live in %USERPROFILE%\\.teambot (DATA_DIR). Program Files is not
     user-writable under UAC, so writing log/latch next to the installed
     exe would silently fail (log() swallows the exception) and the stop
     latch would never persist. DATA_DIR is created at import time.
     >>> The uninstaller deletes both old ({app}) and new (DATA_DIR)
     >>> locations — see teambot.iss [UninstallDelete]. [v2.5]
 20. VERSION_STAMP is no longer a stale literal: the installer writes
     {app}\\version.txt (its own MyAppVersion) and the sidekick reads it
     at import. Fallback remains "1.56.170" ONLY for the legacy manual
     C:\teambot deployment which never gets a version.txt. Update or
     drop that fallback when the exe finally carries its own version.
 21. Tray artwork: the installer now ships the official robot logo as
     {app}\\teambot_icon.ico (shortcuts + setup exe + PyInstaller exe all
     reference it) and {app}\\teambot_icon.png (loaded by _load_base_icon
     below). The orange placeholder mark is retired from installed
     machines.
 22. App-language activation (the "安装选中文 → 装好自动激活中文版"
     feature): the installer wizard's Language Selection page (default
     English, dropdown offers 简体中文) drops {app}\\app_language.txt
     ("en" / "zh-CN", /ZHLANG forces zh-CN for unattended installs). The
     sidekick consumes it via apply_app_language() in main() BEFORE
     spawning the server — json-merge into %USERPROFILE%%\\.teambot\\
     config.json ("language" key only, every other key preserved), which
     is exactly where config.py + the Admin panel read it. The marker is
     deleted after consumption (one-shot); an upgrade re-issues it.
 23. PYTHONIOENCODING=utf-8 injected into every spawned teambot.exe: the
     frozen exe prints emoji status lines (from the first-run autostart
     code) and UnicodeEncodeError-crashed INSTANTLY on GBK consoles
     (cp936) — the second half of the "tray up, service never starts"
     report (the first half was item 18's wrong APP_DIR). The product
     entrypoint now also self-guards (main.py _ensure_stdio_never_raises),
     so this env is belt-and-suspenders for exes that are already
     deployed and cannot be rebuilt.

v2.4 changelog (2026-11-09, user feedback: tray right-click no longer
responds at all):
 13. Deadlock fix (root cause proven with py-spy on the live frozen
     process): spawn_server() held _child_lock (L281) and then called
     ensure_port_free(), which re-acquired the SAME threading.Lock
     (L258). threading.Lock is NOT reentrant, so the monitor thread
     deadlocked itself the moment a respawn found the port held by a
     non-child process — exactly the post-consolidate state: _child
     points at the killed original (3760) while the self-replicated
     duplicate (15292) holds the port. The user then clicked Start
     Service, whose handler ran ON the pystray pump thread and blocked
     on the same lock — the whole tray froze. py-spy stack proof:
     MainThread: act_start -> spawn_server(L281); monitor thread:
     spawn_server(L285) -> ensure_port_free(L258). Fix: _child_lock is
     now an RLock AND ensure_port_free() runs outside the lock.
 14. Healthy-holder adoption: ensure_port_free no longer taskkills a
     port holder that (a) answers HTTP and (b) really is teambot.exe —
     it adopts it into _child via the _AdoptedProc shim instead. This
     also defuses the second half of the incident: the 19:46
     false-positive DOWN (a single 3s health-check timeout) would
     otherwise have spawned a second server and taskkilled the healthy
     holder WITH the user's live browser sessions. A wedged teambot
     (no HTTP answer) is still killed, and a non-teambot squatter is
     still evicted.
 15. Menu actions never block the pump: Start/Stop Service run their
     process work in a daemon thread (pystray invokes on_clicked on the
     main thread; any blocking call there freezes the whole menu — the
     2026-11-09 freeze was exactly that via act_start -> spawn_server).
     Exit keeps a bounded synchronous stop because the process is
     quitting anyway.
 16. Respawn of a WEDGED child finally works: pre-v2.4 the respawn path
     no-op'd forever on "child already running" whenever the child
     process lived but the service did not answer (the 08:49-09:14
     miss=1..501 log streak). monitor now calls spawn_server(replace=True):
     after the 150s unresponsive grace the stale child is killed and a
     fresh one is spawned (its duplicate pair inherits TEAMBOT_VERSION,
     so the version stamp survives consolidation).
 17. Startup banner version made real (_SIDEKICK_VERSION) — v2.3 kept
     printing "v2.2 starting" because the banner string was never
     bumped.

v2.2 changelog (2026-11-08, user feedback: black cmd window flashes on
Start/Stop Service clicks; the first-run wizard STILL pops on every
launch):
  8. Console-flash fix: every subprocess call (netstat probe, taskkill in
     stop_server / consolidate / ensure_port_free) now carries
     CREATE_NO_WINDOW. pythonw has no console to inherit, so each console
     tool used to open a fresh black window on every menu click.
  9. Stop Service actually stops: a user stop sets a persistent latch
     (C:\\teambot\\sidekick_stop_latch). The monitor no longer
     auto-respawns a deliberately stopped service (v2.1 resurrected it
     within 2-3s — and every resurrection opened a fresh unplanted
     instance). The latch survives sidekick restarts and reboots until
     Start Service (or Exit) clears it.
 10. Instant setup-marker planting: between exe spawn and the first
     monitor tick there is a 5-8s window where the server already answers
     but the extraction dir has no pwd.txt yet — the first-run wizard
     pops exactly there (users open the UI right after starting).
     spawn_server now watches for the new instance's _MEI dir and plants
     the marker the moment extraction creates it, well before the port
     binds. Monitor-tick planting stays as backstop.
 11. Data-home marker: when the running server proves setup is complete
     (401 login_required / needs_setup=false), the marker is mirrored to
     ~\\.teambot\\pwd.txt for the setupfix exe build (v1.56.170-setupfix,
     next exe rebuild). A genuinely fresh install (needs_setup=true)
     keeps its first-run wizard — never planted there.

PyInstaller onefile note (learned 2026-11-08, pid 2812 live autopsy):
the exe is a TWO-PROCESS pair — the bootloader parent extracts
%TEMP%\\_MEI<pid>x and re-launches itself as the application child
(skips extraction, maps DLLs from the parent's dir, holds the port).
The child's __file__ resolves pwd.txt inside the PARENT's _MEI dir;
the duplicate-process consolidation keeps the port holder (the child).

v2.1 changelog (2026-11-08, user feedback: first-run wizard pops on EVERY
launch):
  5. Setup-marker planter: the deployed exe (pre-setupfix build) resolves the
     wizard marker pwd.txt inside its per-run _MEIxxxx temp dir (wiped at
     exit), so the wizard re-appears every start. The sidekick now plants
     pwd.txt into every live teambot-signed _MEI dir (web/ present),
     idempotently, at startup and on every monitor tick.
  6. Orphan _MEI cleanup: hard-killed exe instances leave dead _MEI dirs
     behind; startup and hourly sweeps remove old ones (a live dir cannot be
     renamed — DLL locks make that failure the safety guard).
  7. Healthy-server adoption at startup: if a teambot.exe --server already
     serves the port, the sidekick adopts it instead of bouncing it —
     sidekick restarts no longer drop user sessions.

v2.0 changelog (2026-11-08, user feedback: right-click menu dead / tray icons
inconsistent / menu showed "Start Service" while the service was running):

  1. service_running(): ANY HTTP answer now counts as UP. The admin login
     gate makes anonymous /api/status return 401 — v1.0 misread that as
     "service down" (red icon + Start Service while running + pointless
     respawn cycles). urllib HTTPError now means alive; only socket
     errors/timeouts mean down.
  2. Icon unification: base artwork is C:\\teambot\\teambot_icon.png — the
     same art as the app (orange rounded square, white infinity mark) —
     with a small state badge dot (green running / amber starting / red
     stopped). The old hand-drawn robot remains only as fallback if the
     PNG is missing.
  3. Single-instance consolidation: the frozen exe leaves a duplicate
     --server process behind (two identical processes, port held by one of
     them). The monitor adopts the port holder as authoritative and kills
     duplicate teambot.exe processes (capped: once per session, self-heals
     via respawn if the kill cascades).
  4. Tray icon promoted to always-visible on Win11 (NotifyIconSettings
     IsPromoted=1) — new icons otherwise land hidden in the overflow
     flyout, which reads as "no tray icon / nothing to right-click".

Menu:
  TeamBot - Running/Stopped (dynamic)
  Open Chat UI (default / left-click)
  Open Admin Panel
  Open Workspace
  Auto-start on Boot (checkbox, HKCU Run)
  Start / Stop Service (mutually exclusive, state-driven)
  Exit

Log: C:\\teambot\\teambot_tray.log
"""
import os
import sys
import time
import json
import ctypes
import subprocess
import threading
import traceback
from datetime import datetime

# ---------- DPI awareness (better menu coordinates on scaled displays) ----------
try:
    ctypes.windll.shcore.SetProcessDpiAwareness(1)
except Exception:
    try:
        ctypes.windll.user32.SetProcessDPIAware()
    except Exception:
        pass

IS_PYTHONW = sys.executable.lower().endswith("pythonw.exe") or not sys.stdout

# [v2.5 item 18] APP_DIR = wherever THIS script lives. The Inno Setup
# installer deploys to {autopf}\teambot; the legacy manual deployment
# copies the script into C:\teambot — dirname(__file__) is right for both.
if getattr(sys, "frozen", False):
    APP_DIR = os.path.dirname(os.path.abspath(sys.executable))
else:
    APP_DIR = os.path.dirname(os.path.abspath(__file__))
EXE = os.path.join(APP_DIR, "teambot.exe")
DATA_DIR = os.path.expanduser(r"~\.teambot")
try:
    os.makedirs(DATA_DIR, exist_ok=True)
except Exception:
    pass
# [v2.5 item 19] log + stop latch live in DATA_DIR (Program Files is not
# user-writable; the installer's [UninstallDelete] covers both locations).
LOG_FILE = os.path.join(DATA_DIR, "teambot_tray.log")
ICON_FILE = os.path.join(APP_DIR, "teambot_icon.png")
WORKSPACE_DIR = os.path.join(DATA_DIR, "data", "workspace")
PORT = 8767
HOST = "0.0.0.0"
RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
RUN_NAME = "TeamBot"
CHAT_URL = "http://127.0.0.1:%d/ui/chat/chat_container.html" % PORT
ADMIN_URL = "http://127.0.0.1:%d/ui/" % PORT

PYTHONW = sys.executable.replace("python.exe", "pythonw.exe") if sys.executable.lower().endswith("python.exe") else sys.executable

TESTMODE = bool(os.environ.get("TB_TRAY_TESTMODE"))

_NO_WINDOW = 0x08000000  # CREATE_NO_WINDOW: console tools must never flash [v2.2]

# [v2.3/v2.5 item 20] Version stamp injected into every spawned teambot.exe.
# The installer writes {app}\\version.txt (its MyAppVersion); we read it so
# installed machines always report the packaged version. The literal below
# is ONLY the legacy-manual-deployment fallback (no version.txt there).
# Empty string disables injection. Env outranks the exe's own version —
# update/remove both when the exe is rebuilt with its own version source.
VERSION_STAMP = "1.56.170"
try:
    _vtxt = os.path.join(APP_DIR, "version.txt")
    if os.path.exists(_vtxt):
        with open(_vtxt, "r", encoding="utf-8-sig") as f:
            _v = (f.read() or "").strip()
        if _v:
            VERSION_STAMP = _v
except Exception:
    pass

_SIDEKICK_VERSION = "2.5"  # banner truth [v2.5]

# [v2.5 item 22] Installer-driven app language. The Inno Setup wizard writes
# {app}\app_language.txt ("en" or "zh-CN") from the Language Selection page
# (or /ZHLANG for unattended installs). The sidekick consumes the marker
# BEFORE spawning the server: it json-merges "language" into
# %USERPROFILE%\.teambot\config.json — json.load/dump, so a config that
# already holds other keys (or UTF-8 strings) survives untouched. This is
# how "安装时选中文 → 装好自动激活中文版" is implemented; the server reads
# config.language at startup (config.py default "en", Admin persists zh-CN).
APP_LANG_FILE = os.path.join(APP_DIR, "app_language.txt")


def apply_app_language():
    """Consume {app}\app_language.txt -> config.json "language" (one-shot)."""
    if not os.path.exists(APP_LANG_FILE):
        return
    lang = ""
    try:
        with open(APP_LANG_FILE, "r", encoding="utf-8-sig") as f:
            lang = (f.read() or "").strip()
    except Exception as e:
        log("apply_app_language: marker read failed: %r" % e)
    if lang:
        try:
            cfg_path = os.path.join(DATA_DIR, "config.json")
            data = {}
            if os.path.exists(cfg_path):
                with open(cfg_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                if not isinstance(data, dict):
                    data = {}
            needs_write = data.get("language") != lang
            data["language"] = lang
            if needs_write or not os.path.exists(cfg_path):
                tmp = cfg_path + ".tmp"
                with open(tmp, "w", encoding="utf-8") as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                os.replace(tmp, cfg_path)
            log("apply_app_language: config.json language=%s" % lang)
        except Exception as e:
            log("apply_app_language failed: %r" % e)
    try:
        os.remove(APP_LANG_FILE)  # consumed
    except Exception:
        pass


COLOR_OK = "#27AE60"
COLOR_ERR = "#E74C3C"
COLOR_STARTING = "#F39C12"


def log(msg):
    line = "[%s] %s" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), msg)
    try:
        with open(LOG_FILE, "a", encoding="utf-8") as f:
            f.write(line + "\n")
    except Exception:
        pass
    if not IS_PYTHONW:
        try:
            print(line)
        except Exception:
            pass


# ---------- single instance via named mutex ----------
def already_running():
    k32 = ctypes.windll.kernel32
    k32.CreateMutexW.restype = ctypes.c_void_p
    k32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
    k32.GetLastError.restype = ctypes.c_uint
    ctypes.windll.kernel32.CreateMutexW(None, False, "TeamBotTraySidekickMutex")
    return ctypes.GetLastError() == 183  # ERROR_ALREADY_EXISTS


# ---------- user-stop latch (v2.2) ----------
# Clicking Stop Service must KEEP the service stopped: v2.1's monitor
# auto-respawned a deliberate stop within 2-3 seconds (and every respawn
# re-opened the unplanted wizard window). The latch persists in a flag
# file so a reboot/autostart does not resurrect the service either;
# Start Service (or Exit) clears it.
LATCH_FILE = os.path.join(DATA_DIR, "sidekick_stop_latch")  # [v2.5 item 19]
STOP_LATCH = {"on": False}


def read_stop_latch():
    try:
        return os.path.exists(LATCH_FILE)
    except Exception:
        return False


def write_stop_latch(on):
    STOP_LATCH["on"] = bool(on)
    try:
        if on:
            with open(LATCH_FILE, "w", encoding="utf-8") as f:
                f.write("user clicked Stop Service\n")
        elif os.path.exists(LATCH_FILE):
            os.remove(LATCH_FILE)
    except OSError as e:
        log("write_stop_latch(%s) error: %r" % (on, e))


# ---------- teambot.exe process management ----------
# RLock, NOT Lock [v2.4 item 13]: spawn_server legitimately calls
# ensure_port_free while holding this lock, and ensure_port_free reads
# _child under the same lock again. A plain Lock self-deadlocked exactly
# there and froze the whole tray (proven by py-spy on the live process:
# monitor at L258 under spawn_server's L281, then act_start blocked the
# pump on the same lock).
_child_lock = threading.RLock()
_child = {"proc": None}


def find_running_tebobot_pids():
    """PIDs of teambot.exe processes (any mode)."""
    pids = []
    try:
        import psutil
        for p in psutil.process_iter(["pid", "name"]):
            if (p.info["name"] or "").lower() == "teambot.exe":
                pids.append(p.info["pid"])
    except Exception as e:
        log("find_running_tebobot_pids error: %r" % e)
    return pids


def port_holder_pid(port=PORT):
    """PID currently LISTENING on port, via netstat -ano parse. None if free."""
    try:
        r = subprocess.run(["netstat", "-ano"], capture_output=True, timeout=20,
                           creationflags=_NO_WINDOW)
        lines = r.stdout.decode("utf-8", "replace").splitlines()
        for ln in lines:
            parts = ln.split()
            # TCP  0.0.0.0:8767  0.0.0.0:0  LISTENING  1234
            if len(parts) >= 5 and parts[3].upper() == "LISTENING" and (
                    parts[1].endswith(":%d" % port) or parts[1] == "[::]:%d" % port):
                try:
                    return int(parts[4])
                except ValueError:
                    pass
    except Exception as e:
        log("port_holder_pid error: %r" % e)
    return None


class _AdoptedProc(object):
    """subprocess.Popen-shaped handle for an ADOPTED teambot.exe (started
    outside this sidekick — e.g. the self-replicated duplicate that won
    the port, or a server started manually). Only pid/poll/terminate/
    kill/wait are needed by spawn_server / stop_server / _respawn_needed.
    [v2.4 item 14]"""

    def __init__(self, pid):
        self.pid = pid

    def poll(self):
        try:
            import psutil
            return None if psutil.pid_exists(self.pid) else 0
        except Exception:
            return None  # cannot prove death — assume alive

    def _taskkill(self):
        try:
            subprocess.run(["taskkill", "/F", "/T", "/PID", str(self.pid)],
                           capture_output=True, timeout=15,
                           creationflags=_NO_WINDOW)
        except Exception:
            pass

    def terminate(self):
        self._taskkill()

    def kill(self):
        self._taskkill()

    def wait(self, timeout=None):
        deadline = time.time() + (timeout or 0)
        while time.time() < deadline:
            if self.poll() is not None:
                return 0
            time.sleep(0.2)
        raise TimeoutError("adopted pid %s still running" % self.pid)


def _is_tebobot_pid(pid):
    try:
        import psutil
        return (psutil.Process(pid).name() or "").lower() == "teambot.exe"
    except Exception:
        return False


def ensure_port_free():
    """Make the port usable for a spawn.

    v2.4 item 14: a holder that ANSWERS HTTP and really is teambot.exe is
    ADOPTED, never killed — a false-positive service_down must not bounce
    the user's live sessions. Killing stays for a wedged teambot (no HTTP
    answer = true recovery target) and for a non-teambot squatter.
    """
    holder = port_holder_pid()
    if holder is None:
        return True
    with _child_lock:
        child = _child["proc"]
        child_pid = child.pid if child is not None else None
    if child_pid is not None and holder == child_pid:
        return True  # our own child legitimately holds it
    if service_running() and _is_tebobot_pid(holder):
        log("ensure_port_free: healthy teambot holder pid=%s (child=%s) -> adopt, no kill"
            % (holder, child_pid))
        with _child_lock:
            _child["proc"] = _AdoptedProc(holder)
        return True
    log("ensure_port_free: port %d held by pid=%s (child=%s) -> taskkill" % (PORT, holder, child_pid))
    try:
        subprocess.run(["taskkill", "/F", "/T", "/PID", str(holder)],
                       capture_output=True, timeout=15,
                       creationflags=_NO_WINDOW)
    except Exception as e:
        log("ensure_port_free taskkill error: %r" % e)
    deadline = time.time() + 10
    while time.time() < deadline:
        if port_holder_pid() is None:
            return True
        time.sleep(1)
    log("ensure_port_free: port STILL held after taskkill")
    return False


def spawn_server(replace=False):
    """Start teambot.exe as headless server.

    replace=True [v2.4 item 16]: kill an alive-but-unresponsive child
    first. The monitor's respawn path passes True after the 150s
    unresponsive grace; with a dead child (or no child) it is a no-op,
    and a healthy holder is adopted by ensure_port_free instead of ever
    being killed.
    """
    victim = None
    with _child_lock:
        proc = _child["proc"]
        if proc is not None and proc.poll() is None:
            if not replace:
                log("spawn_server: child already running pid=%s" % proc.pid)
                return proc.pid
            victim = proc
    if victim is not None:
        log("spawn_server: replace=True — killing unresponsive child pid=%s" % victim.pid)
        try:
            victim.terminate()
            try:
                victim.wait(timeout=8)
            except Exception:
                victim.kill()
        except Exception as e:
            log("spawn_server replace kill error: %r" % e)
        with _child_lock:
            if _child["proc"] is victim:
                _child["proc"] = None
    # ensure_port_free OUTSIDE the lock [v2.4 item 13] — it may adopt a
    # healthy holder (filling _child) or evict a wedged one; both can take
    # seconds (netstat/taskkill timeouts) and must not pin the lock.
    ensure_port_free()
    with _child_lock:
        if _child["proc"] is not None and _child["proc"].poll() is None:
            log("spawn_server: adopting healthy holder pid=%s instead of spawning"
                % _child["proc"].pid)
            return _child["proc"].pid
        flags = _NO_WINDOW  # CREATE_NO_WINDOW
        # [v2.3] inject the deployment version stamp (changelog item 12):
        # the frozen exe has no version source, get_version() checks this
        # env var first -> /api/status + all UI stamps report VERSION_STAMP.
        child_env = dict(os.environ)
        if VERSION_STAMP:
            child_env["TEAMBOT_VERSION"] = VERSION_STAMP
        # [v2.5 item 23] legacy-exe rescue: already-deployed exes print emoji
        # status lines and die with UnicodeEncodeError on GBK consoles
        # (cp936) — the visible symptom was "tray starts, service never
        # does". utf-8 stdio for the child makes those old exes survive.
        # New exes carry their own stdio guard (main.py v1.56.172).
        child_env.setdefault("PYTHONIOENCODING", "utf-8")
        try:
            proc = subprocess.Popen(
                [EXE, "--server", "--host", HOST, "--port", str(PORT)],
                cwd=APP_DIR, creationflags=flags, env=child_env,
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                stdin=subprocess.DEVNULL)
            _child["proc"] = proc
            log("spawn_server: started teambot.exe --server pid=%s version_stamp=%s"
                % (proc.pid, VERSION_STAMP or "<none>"))
            threading.Thread(target=spawn_planter, args=(proc.pid,),
                             daemon=True).start()
            return proc.pid
        except Exception as e:
            log("spawn_server FAILED: %r" % e)
            return None


def stop_server():
    """Stop the teambot.exe server (child and, if any, stray instances)."""
    with _child_lock:
        proc = _child["proc"]
        _child["proc"] = None
    if proc is not None and proc.poll() is None:
        try:
            proc.terminate()
            try:
                proc.wait(timeout=8)
            except Exception:
                proc.kill()
            log("stop_server: child terminated")
        except Exception as e:
            log("stop_server error: %r" % e)
    # also kill stray teambot.exe (incl. the port-holding duplicate)
    killed = []
    for pid in find_running_tebobot_pids():
        try:
            subprocess.run(["taskkill", "/F", "/T", "/PID", str(pid)],
                           capture_output=True, timeout=15,
                           creationflags=_NO_WINDOW)
            killed.append(pid)
        except Exception:
            pass
    if killed:
        log("stop_server: taskkill stray pids=%s" % killed)


def service_running(port=PORT):
    """True if the admin port answers with ANY http response.

    The login gate makes anonymous /api/status return 401 — that still
    proves the server is alive. 302 (login redirect), 200, even 404 all
    mean UP. Only socket errors / timeouts mean DOWN. [v2.0 fix]
    """
    import urllib.request
    import urllib.error
    try:
        with urllib.request.urlopen("http://127.0.0.1:%d/api/status" % port, timeout=3) as r:
            return True
    except urllib.error.HTTPError:
        return True  # 401/404/5xx — an HTTP answer means the server lives
    except Exception:
        return False


# ---------- setup wizard marker (v2.1) ----------
MARKER_TEXT = "TeamBot setup completed\n"


def _temp_dir():
    return os.environ.get("TEMP") or os.path.expanduser(r"~\AppData\Local\Temp")


def _is_teambot_mei(path):
    """Teambot onefile extraction signature: a web/ package dir inside."""
    return os.path.isdir(os.path.join(path, "web"))


def _mei_dirs():
    tmp = _temp_dir()
    try:
        return [d for d in os.listdir(tmp)
                if d.lower().startswith("_mei")
                and os.path.isdir(os.path.join(tmp, d))]
    except OSError:
        return []


def plant_setup_marker():
    """Plant the wizard-completion marker into live _MEIxxxx dirs.

    The deployed exe resolves pwd.txt inside its per-run _MEIxxxx temp dir;
    without the marker the first-run wizard re-appears on every launch.
    Planting is idempotent and only touches teambot-signed dirs. [v2.1]
    """
    tmp = _temp_dir()
    planted = []
    for d in _mei_dirs():
        p = os.path.join(tmp, d)
        if not _is_teambot_mei(p):
            continue
        m = os.path.join(p, "pwd.txt")
        if os.path.exists(m):
            continue
        try:
            with open(m, "w", encoding="utf-8") as f:
                f.write(MARKER_TEXT)
            planted.append(d)
        except OSError as e:
            log("plant_setup_marker: %s failed: %r" % (d, e))
    if planted:
        log("plant_setup_marker: planted into %s" % planted)
    return planted


def cleanup_orphan_mei(min_age_s=600):
    """Remove dead teambot _MEIxxxx dirs left by hard-killed instances.

    A LIVE dir cannot be renamed (its DLLs are locked) — the rename failure
    is the safety guard. min_age_s avoids any window during extraction where
    a just-spawned exe has not locked its files yet. [v2.1]
    """
    import shutil
    tmp = _temp_dir()
    now = time.time()
    removed = []
    for d in _mei_dirs():
        p = os.path.join(tmp, d)
        if not _is_teambot_mei(p):
            continue
        try:
            if now - os.path.getctime(p) < min_age_s:
                continue
        except OSError:
            continue
        dead = p + ".dead_mei"
        try:
            os.rename(p, dead)
        except OSError:
            continue  # live (locked) — leave it alone
        shutil.rmtree(dead, ignore_errors=True)
        removed.append(d)
    if removed:
        log("cleanup_orphan_mei: removed %s" % removed)
    return removed


def _mei_dirs_for_pid(pid):
    """_MEI dirs of a freshly spawned exe (bootloader names them _MEI<pid>*)."""
    tmp = _temp_dir()
    pref = "_MEI%d" % pid
    try:
        return [d for d in os.listdir(tmp)
                if d.startswith(pref) and os.path.isdir(os.path.join(tmp, d))]
    except OSError:
        return []


def spawn_planter(pid, max_wait_s=30.0):
    """Plant the wizard marker the instant the new instance's _MEI appears.

    Between exe spawn and the first monitor tick there is a 5-8s window
    where the server already answers but the extraction dir has no
    pwd.txt yet — the first-run wizard pops exactly there (users open
    the UI right after starting). The dir is created at extraction start,
    well before the port binds: poll and plant immediately. [v2.2]
    """
    tmp = _temp_dir()
    deadline = time.time() + max_wait_s
    while time.time() < deadline:
        for d in _mei_dirs_for_pid(pid):
            p = os.path.join(tmp, d)
            if not _is_teambot_mei(p):
                continue
            if os.path.exists(os.path.join(p, "pwd.txt")):
                return  # already marked
            try:
                with open(os.path.join(p, "pwd.txt"), "w", encoding="utf-8") as f:
                    f.write(MARKER_TEXT)
                log("spawn_planter: planted %s (pid=%d, pre-UP)" % (d, pid))
            except OSError as e:
                log("spawn_planter: %s failed: %r" % (d, e))
            return
        time.sleep(0.25)


def server_says_configured(timeout=4):
    """True iff the running server proves first-run setup is complete.

    - 401/403 (login_required): the password gate is on -> configured.
    - JSON needs_setup=false: configured.
    - Any other 200 non-JSON body: the gate redirected to the login page
      -> configured.
    - needs_setup=true: a genuinely fresh install -> NOT configured (the
      first-run wizard must keep showing). No answer -> False (no harm).
    """
    import urllib.request
    import urllib.error
    try:
        with urllib.request.urlopen(
                "http://127.0.0.1:%d/api/setup/status" % PORT, timeout=timeout) as r:
            raw = r.read().decode("utf-8", "replace")
            try:
                body = json.loads(raw)
            except ValueError:
                return True  # non-JSON 200 = login page redirect = gated
            return body.get("needs_setup") is not True
    except urllib.error.HTTPError as e:
        return e.code in (401, 403)  # gated -> password configured
    except Exception:
        return False


def plant_data_home_marker():
    """Mirror the completed-setup marker into the stable data home.

    The current exe ignores it (resolves pwd.txt only in its extraction
    dir); the setupfix build (v1.56.170-setupfix, next exe rebuild)
    resolves it at _data_home()/pwd.txt. Only planted when the server
    proves setup is complete — fresh installs keep their wizard. [v2.2]
    """
    try:
        if not server_says_configured():
            return False
        m = os.path.join(DATA_DIR, "pwd.txt")
        if os.path.exists(m):
            return True
        os.makedirs(DATA_DIR, exist_ok=True)
        with open(m, "w", encoding="utf-8") as f:
            f.write(MARKER_TEXT)
        log("plant_data_home_marker: planted %s" % m)
        return True
    except Exception as e:
        log("plant_data_home_marker error: %r" % e)
        return False


def consolidate():
    """Keep exactly one teambot.exe: the one actually serving the port.

    The frozen exe tends to leave a duplicate --server process (identical
    cmdline). The port holder is authoritative; duplicates are killed.
    """
    pids = find_running_tebobot_pids()
    if len(pids) <= 1:
        return
    holder = port_holder_pid()
    if holder is None or holder not in pids:
        return
    extras = [p for p in pids if p != holder]
    if not extras:
        return
    log("consolidate: pids=%s holder=%s -> killing extras %s" % (pids, holder, extras))
    for pid in extras:
        try:
            subprocess.run(["taskkill", "/F", "/PID", str(pid)],
                           capture_output=True, timeout=15,
                           creationflags=_NO_WINDOW)
        except Exception as e:
            log("consolidate taskkill %s error: %r" % (pid, e))


_CONSOL = {"n": 0, "t": 0.0}


def maybe_consolidate():
    """Rate-limited consolidation (max once per 120s, max 8 per session)."""
    now = time.time()
    if now - _CONSOL["t"] < 120 or _CONSOL["n"] >= 8:
        return
    _CONSOL["t"] = now
    _CONSOL["n"] += 1
    try:
        consolidate()
    except Exception as e:
        log("maybe_consolidate error: %r" % e)


# ---------- autostart (HKCU Run -> pythonw sidekick) ----------
def autostart_command():
    return '"%s" "%s"' % (PYTHONW, os.path.join(APP_DIR, "teambot_tray.py"))


def check_autostart():
    try:
        import winreg
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as k:
            val, _ = winreg.QueryValueEx(k, RUN_NAME)
            return "teambot_tray" in val
    except Exception:
        return False


def set_autostart(enable):
    import winreg
    with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY, 0, winreg.KEY_SET_VALUE) as k:
        if enable:
            winreg.SetValueEx(k, RUN_NAME, 0, winreg.REG_SZ, autostart_command())
        else:
            try:
                winreg.DeleteValue(k, RUN_NAME)
            except FileNotFoundError:
                pass
    log("set_autostart(%s) done" % enable)


def promote_tray_visible():
    """Win11: mark our tray icon as always visible (NotifyIconSettings).

    Without this, freshly registered icons sit hidden inside the overflow
    flyout and the user believes there is no tray icon at all. [v2.0]
    """
    try:
        import winreg
        root = winreg.HKEY_CURRENT_USER
        base = r"Control Panel\NotifyIconSettings"
        with winreg.OpenKey(root, base, 0, winreg.KEY_READ) as k:
            subkeys = []
            i = 0
            while True:
                try:
                    subkeys.append(winreg.EnumKey(k, i))
                    i += 1
                except OSError:
                    break
        for sub in subkeys:
            try:
                path = base + "\\" + sub
                with winreg.OpenKey(root, path, 0, winreg.KEY_READ | winreg.KEY_WRITE) as sk:
                    try:
                        exe = winreg.QueryValueEx(sk, "ExecutablePath")[0]
                    except OSError:
                        continue
                    if exe and exe.lower().rstrip() == PYTHONW.lower():
                        winreg.SetValueEx(sk, "IsPromoted", 0, winreg.REG_DWORD, 1)
                        log("promote_tray_visible: IsPromoted=1 (%s)" % exe)
            except OSError:
                continue
    except Exception as e:
        log("promote_tray_visible skipped: %r" % e)


# ---------- tray artwork [v2.0: official icon + state badge] ----------
def _load_base_icon(size=64):
    from PIL import Image
    try:
        img = Image.open(ICON_FILE).convert("RGBA")
        img.thumbnail((size, size))
        canvas = Image.new("RGBA", (size, size), (0, 0, 0, 0))
        canvas.alpha_composite(img, ((size - img.width) // 2, (size - img.height) // 2))
        return canvas
    except Exception:
        return None


def _draw_robot(color, size=64):
    """Legacy fallback artwork (used only when teambot_icon.png is missing)."""
    from PIL import Image, ImageDraw
    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
    d = ImageDraw.Draw(img)
    m, r = 2, 14
    d.rounded_rectangle([m, m, size - m, size - m], radius=r, fill=color)
    d.rounded_rectangle([28, 0, 36, 10], radius=2, fill=color)
    d.ellipse([25, 0, 39, 8], fill=color)
    d.rounded_rectangle([6, 14, 58, 58], radius=10, fill=color)
    return img


def _hex_rgb(c):
    c = c.lstrip("#")
    return tuple(int(c[i:i + 2], 16) for i in (0, 2, 4))


def draw_icon(color, size=64):
    """Official TeamBot artwork + state badge dot (bottom-right)."""
    from PIL import ImageDraw
    base = _load_base_icon(size)
    if base is None:
        base = _draw_robot(color, size)
    img = base.copy()
    d = ImageDraw.Draw(img)
    r = size // 6
    cx, cy = size - r - 3, size - r - 3
    d.ellipse([cx - r, cy - r, cx + r, cy + r],
              fill=_hex_rgb(color) + (255,),
              outline=(255, 255, 255, 235), width=2)
    return img


def notify(icon, msg, title="TeamBot"):
    try:
        icon.notify(msg, title)
    except Exception:
        pass


# ---------- tray state / menu (module-level for testability) ----------
STATE = {"running": None}  # None=starting/unknown, True=up, False=stopped


def open_url(url):
    try:
        os.startfile(url)  # noqa
    except Exception as e:
        log("open_url(%s) failed: %r" % (url, e))


def act_chat(icon, item):
    open_url(CHAT_URL)


def act_admin(icon, item):
    open_url(ADMIN_URL)


def act_workspace(icon, item):
    try:
        os.makedirs(WORKSPACE_DIR, exist_ok=True)
        os.startfile(WORKSPACE_DIR)  # noqa
    except Exception as e:
        log("act_workspace failed: %r" % e)


def act_toggle_autostart(icon, item):
    try:
        new_state = not check_autostart()
        set_autostart(new_state)
        notify(icon, "Auto-start on boot enabled" if new_state else "Auto-start on boot disabled")
    except Exception as e:
        log("act_toggle_autostart failed: %r" % e)
        notify(icon, "Failed: %s" % e)


def _off_pump(fn):
    """Run menu-action work OFF the pystray pump thread [v2.4 item 15].
    pystray invokes on_clicked handlers on the main thread; any blocking
    call there (lock wait, taskkill, HTTP) freezes the whole menu — the
    2026-11-09 freeze was exactly that via act_start -> spawn_server."""
    threading.Thread(target=fn, daemon=True).start()


def act_start(icon, item):
    write_stop_latch(False)  # explicit start overrides the stop latch [v2.2]
    if TESTMODE:
        log("TESTMODE: act_start — latch cleared only (no real process)")
        return
    _off_pump(lambda: (spawn_server(),
                       notify(icon, "Service starting...", "TeamBot")))


def act_stop(icon, item):
    write_stop_latch(True)  # user intent: stay stopped, no auto-respawn [v2.2]
    if TESTMODE:
        log("TESTMODE: act_stop — latch set only (no real process)")
        return
    _off_pump(lambda: (stop_server(),
                       notify(icon, "Service stopped", "TeamBot")))


def act_exit(icon, item):
    log("exit requested from tray menu")
    write_stop_latch(False)  # relaunching the sidekick means wanting the stack [v2.2]
    try:
        stop_server()  # bounded (~8s wait + 15s taskkill caps); process is exiting anyway
    except Exception as e:
        log("act_exit stop_server error: %r" % e)
    icon.stop()


def status_text(*args):
    r = STATE["running"]
    if r:
        return "TeamBot - Running"
    return "TeamBot - Starting..." if r is None else "TeamBot - Stopped"


def _checked(*args):
    return check_autostart()


def build_menu():
    from pystray import Menu, MenuItem
    return Menu(
        MenuItem(status_text, None, enabled=False),
        Menu.SEPARATOR,
        MenuItem("Open Chat UI", act_chat, default=True),
        MenuItem("Open Admin Panel", act_admin),
        MenuItem("Open Workspace", act_workspace),
        Menu.SEPARATOR,
        MenuItem("Auto-start on Boot", act_toggle_autostart, checked=_checked),
        Menu.SEPARATOR,
        MenuItem("Start Service", act_start,
                 visible=lambda *a: STATE["running"] is False),
        MenuItem("Stop Service", act_stop,
                 visible=lambda *a: STATE["running"] is True),
        Menu.SEPARATOR,
        MenuItem("Exit", act_exit),
    )


def refresh_icon(icon):
    try:
        icon.menu = build_menu()
        icon.update_menu()
    except Exception:
        pass


# ---------- monitor thread ----------
_last_spawn = {"t": 0.0}


def _respawn_needed(ok):
    """Respawn policy: quick retry when child died; long grace while it boots."""
    if ok:
        return False
    now = time.time()
    with _child_lock:
        proc = _child["proc"]
    child_alive = proc is not None and proc.poll() is None
    if not child_alive and now - _last_spawn["t"] > 10:
        return True   # child gone: restart quickly
    if now - _last_spawn["t"] > 150:
        return True   # child alive but unresponsive for too long: replace
    return False


_last_cleanup = {"t": 0.0}
_DH_MARKER = {"done": False}  # data-home marker planted? [v2.2]


def monitor(icon):
    while True:
        try:
            ok = service_running()
            prev = STATE["running"]
            STATE["running"] = ok
            if ok and not prev:
                try:
                    icon.icon = draw_icon(COLOR_OK)
                except Exception:
                    pass
                refresh_icon(icon)
                if prev is not None:
                    notify(icon, "Service is running (port %d)" % PORT)
                log("monitor: service UP")
            elif not ok and prev:
                try:
                    icon.icon = draw_icon(COLOR_ERR)
                except Exception:
                    pass
                refresh_icon(icon)
                log("monitor: service DOWN")
            if TESTMODE:
                pass  # never touch real processes under test
            elif ok:
                maybe_consolidate()
                plant_setup_marker()  # idempotent; covers every (re)spawn [v2.1]
                if not _DH_MARKER["done"] and plant_data_home_marker():
                    _DH_MARKER["done"] = True  # [v2.2] one-shot data-home marker
                if time.time() - _last_cleanup["t"] > 3600:
                    _last_cleanup["t"] = time.time()
                    cleanup_orphan_mei()
            elif not STOP_LATCH["on"] and _respawn_needed(False):
                log("monitor: service down — respawn cycle")
                _last_spawn["t"] = time.time()
                # replace=True [v2.4 item 16]: a child that is alive but
                # stayed unresponsive for 150s+ (the _respawn_needed grace)
                # must be replaced — pre-v2.4 this no-op'd forever on
                # "child already running". For a dead child, spawn_server
                # adopts a healthy holder or spawns fresh; a false-positive
                # DOWN can no longer bounce live sessions. [v2.4 items 13/14]
                spawn_server(replace=True)
            time.sleep(5 if ok else 3)
        except Exception as e:
            log("monitor error: %r\n%s" % (e, traceback.format_exc()))
            time.sleep(5)


# ---------- main ----------
def main():
    if already_running():
        log("another sidekick instance already running — exit")
        return
    STOP_LATCH["on"] = read_stop_latch()
    log("=== TeamBot tray sidekick v%s starting (pid=%s, python=%s, stop_latch=%s) ==="
        % (_SIDEKICK_VERSION, os.getpid(), sys.version, STOP_LATCH["on"]))

    # [v2.5 item 22] activate the installer-chosen app language BEFORE the
    # server spawns, so the first UI already comes up in that language
    apply_app_language()

    import pystray

    # take over / adopt existing teambot instances
    if TESTMODE:
        log("TESTMODE: not touching teambot.exe processes")
    else:
        old = find_running_tebobot_pids()
        holder = port_holder_pid()
        adopted = False
        if holder in old and service_running():
            # a healthy headless server is already up (e.g. sidekick restart)
            # — adopt it instead of bouncing user sessions [v2.1]
            try:
                import psutil
                cl = psutil.Process(holder).cmdline()
            except Exception:
                cl = []
            if any("--server" in str(a) for a in cl):
                log("startup: adopting healthy --server pid=%s (no restart)" % holder)
                adopted = True
            else:
                log("startup: port holder pid=%s is not --server (broken tray?)" % holder)
        if not adopted:
            if STOP_LATCH["on"]:
                # user explicitly stopped the service — keep it stopped [v2.2]
                log("stop latch set — service stays stopped (user request)")
                if old:
                    log("stop latch: killing leftover teambot.exe pids=%s" % old)
                    stop_server()
            else:
                if old:
                    log("existing teambot.exe pids=%s — stopping (broken internal tray)" % old)
                    stop_server()
                    time.sleep(2)
                spawn_server()
                _last_spawn["t"] = time.time()

    # give the exe's duplicate process time to appear, then consolidate once
    _CONSOL["t"] = time.time() - 100  # first maybe_consolidate after ~20s

    plant_setup_marker()   # immediate relief for the CURRENT instance [v2.1]
    cleanup_orphan_mei()   # dead dirs from hard-killed runs [v2.1]
    promote_tray_visible()

    icon = pystray.Icon("teambotsidekick", draw_icon(COLOR_STARTING),
                        "TeamBot", build_menu())
    threading.Thread(target=monitor, args=(icon,), daemon=True).start()

    # IMPORTANT: pystray pump runs in the MAIN thread here (Windows pattern)
    try:
        icon.run()
    except BaseException:
        log("tray run crashed:\n%s" % traceback.format_exc())
    log("=== sidekick exit ===")


if __name__ == "__main__":
    try:
        main()
    except BaseException:
        tb = traceback.format_exc()
        log("FATAL:\n%s" % tb)
        try:
            ctypes.windll.user32.MessageBoxW(0, tb, "TeamBot Tray Sidekick - Error", 0x10)
        except Exception:
            pass
