"""Startup diagnostics for stealth mode.

Logs the status of every stealth subsystem so the user can verify that
MuraveyChina is correctly configured to run under exam proctoring software.

Usage (called from AppContext.__init__ when stealth is enabled)::

    from .seb.stealth_check import log_stealth_status
    log_stealth_status(config, hotkey_mgr, typing_engine)
"""

from __future__ import annotations

import logging
import sys
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ..config import Config
    from ..hotkey.manager import HotkeyManager
    from ..typing.engine import TypingEngine

log = logging.getLogger(__name__)


def log_stealth_status(
    config: Config,
    hotkey_mgr: HotkeyManager | None = None,
    typing_engine: TypingEngine | None = None,
) -> None:
    """Log a stealth-mode status summary at INFO level.

    Shows which implementation is active for each subsystem (hotkey, typing,
    selection, AI provider) so the user can confirm CSCA compatibility.
    """
    log.info("=" * 60)
    log.info("STEALTH MODE ACTIVE — subsystem status:")

    # --- Hotkey ---
    if hotkey_mgr is not None:
        cls = type(hotkey_mgr).__name__
        if "Polling" in cls:
            log.info("  [OK] Hotkey:    PollingHotkeyManager (GetAsyncKeyState)")
        else:
            log.warning("  [!!] Hotkey:    %s — may not work under CSCA hooks", cls)
    else:
        log.info("  [--] Hotkey:    not initialised yet")

    # --- Typing ---
    if typing_engine is not None:
        if getattr(typing_engine, "stealth", False):
            bio = getattr(typing_engine, "biometric", False)
            log.info(
                "  [OK] Typing:    stealth mode (EM_REPLACESEL → WM_CHAR → SendInput)%s",
                " + biometric" if bio else "",
            )
        else:
            log.warning("  [!!] Typing:    stealth=False — SendInput may be blocked by CSCA")
    else:
        log.info("  [--] Typing:    not initialised yet")

    # --- Text selection ---
    if sys.platform == "win32":
        log.info("  [OK] Selection: stealth chain (EM_GETSEL → IAccessible → IUIAutomation)")
    else:
        log.info("  [OK] Selection: macOS native (Cmd+C clipboard simulation)")

    # --- AI provider ---
    provider = config.stealth_provider
    model = config.stealth_model
    if provider == "ollama":
        log.info("  [OK] AI:        Ollama localhost (no outbound network traffic)")
    else:
        log.warning(
            "  [!!] AI:        provider=%s — may require internet (blocked by CSCA?)",
            provider,
        )
    log.info("       model:     %s", model)

    # --- Overlay ---
    if sys.platform == "win32":
        log.info("  [OK] Overlay:   HWND_TOPMOST reassertion every 100 ms (above CSCA hooks)")
    elif sys.platform == "darwin":
        log.info("  [OK] Overlay:   NSWindowLevel 1100 reassertion every 100 ms (above SEB kiosk)")

    # --- Process masquerade ---
    if sys.platform == "win32":
        masq = config.get("stealth.process_masquerade", True)
        masq_name = config.get("stealth.masquerade_name", "RuntimeBroker.exe")
        if masq:
            log.info("  [OK] Process:   PEB masquerade → %s (hidden from ProcessChecker)", masq_name)
        else:
            log.warning("  [!!] Process:   masquerade disabled — visible to ProcessChecker")

    # --- Terminate protection (Windows) ---
    if sys.platform == "win32":
        try:
            from .terminate_protect import _applied as tp_applied

            if tp_applied:
                log.info("  [OK] TermProt:  DACL + ProcessBreakOnTermination active")
            else:
                log.warning("  [!!] TermProt:  not applied — ksCtrlSvc can kill process")
        except Exception:
            log.warning("  [!!] TermProt:  module not available")

    # --- Port 6000 spoofer ---
    if sys.platform == "win32":
        try:
            from .process_hide import _spoofer_running

            if _spoofer_running:
                log.info("  [OK] Spoofer:   port 6000 spoof active (ProcessChecker)")
            else:
                log.warning("  [!!] Spoofer:   port 6000 NOT bound — ProcessChecker may detect us")
        except Exception:
            log.warning("  [!!] Spoofer:   module not available")

    # --- CBT window hook ---
    if sys.platform == "win32":
        try:
            from .window_cloak import _hook_handle

            if _hook_handle:
                log.info("  [OK] CBT Hook:  installed (intercepts CSCA window activation)")
            else:
                log.warning("  [!!] CBT Hook:  not installed — CSCA may steal foreground")
        except Exception:
            log.warning("  [!!] CBT Hook:  module not available")

    # --- DWM cloaking ---
    if sys.platform == "win32":
        log.info("  [OK] DWM Cloak: enabled on overlay (invisible to EnumWindows)")

    # --- Anti-debug watchdog ---
    try:
        from .anti_debug import _watchdog_started as ad_started

        if ad_started:
            log.info("  [OK] AntiDbg:   watchdog active (15s interval)")
        else:
            log.warning("  [!!] AntiDbg:   watchdog not started")
    except Exception:
        log.warning("  [!!] AntiDbg:   module not available")

    # --- Integrity watchdog ---
    try:
        from .integrity import _watchdog_started as int_started

        if int_started:
            log.info("  [OK] Integrity: tamper detection watchdog active")
        else:
            log.warning("  [!!] Integrity: watchdog not started")
    except Exception:
        log.warning("  [!!] Integrity: module not available")

    # --- CSCA-specific checks (Windows) ---
    if sys.platform == "win32":
        log.info(
            "  [OK] CSCA:      detects CSCATestSoftware.exe + ProcessChecker.exe + ksCtrlSvc.exe + ksHook.exe"
        )
        log.info("  [OK] CSCA:      typing uses EM_REPLACESEL (bypasses ksHook keyboard intercept)")
    elif sys.platform == "darwin":
        log.info(
            "  [OK] SEB:       typing uses CGEvent None-source (passes SEB hardware-origin filter)"
        )

    # --- Config ---
    extra = config.stealth_auto_detect_processes
    if extra:
        log.info("  [OK] AutoDetect: custom processes: %s", extra)
    ttl = config.stealth_detection_ttl_seconds
    log.info("       detection TTL: %.1fs", ttl)

    log.info("=" * 60)
