"""Centralized stealth initialization for CSCA compatibility.

Activates all stealth protections in the correct order.
Each layer is optional and fails gracefully — any subset helps.

Call order:
1. Terminate protection (DACL + critical process flag)
2. Advanced process hiding (thread names, port 6000 spoofer)
3. CBT window hook (intercept CSCA window activations)

Called from app.py AFTER PEB masquerade and watchdog.
"""

from __future__ import annotations

import logging
import sys

log = logging.getLogger(__name__)


def init_csca_protections() -> dict[str, bool]:
    """Initialize all CSCA-specific stealth protections.

    Returns a dict of protection_name → success status.
    Safe no-op on non-Windows platforms.
    """
    results: dict[str, bool] = {}

    if sys.platform != "win32":
        return results

    # Layer 1: Terminate protection — block ksCtrlSvc from killing us
    try:
        from .terminate_protect import apply_terminate_protection

        ok = apply_terminate_protection()
        results["terminate_protect"] = ok
        if ok:
            log.info("Terminate protection active (DACL + critical process)")
        else:
            log.debug("Terminate protection: partial or unavailable (non-admin)")
    except Exception as exc:
        results["terminate_protect"] = False
        log.debug("Terminate protection skipped: %s", exc)

    # Layer 2: Advanced process hiding — fool ProcessChecker port 6000
    try:
        from .process_hide import apply_advanced_hiding

        apply_advanced_hiding()
        results["process_hide"] = True
        log.info("Advanced process hiding active (threads, port spoofer)")
    except Exception as exc:
        results["process_hide"] = False
        log.debug("Advanced hiding skipped: %s", exc)

    # Layer 3: CBT window hook — intercept CSCA kiosk activations
    try:
        from .window_cloak import install_cbt_hook

        ok = install_cbt_hook()
        results["cbt_hook"] = ok
        if ok:
            log.info("CBT window hook installed")
    except Exception as exc:
        results["cbt_hook"] = False
        log.debug("CBT hook skipped: %s", exc)

    # Layer 4: Network protection — survive CSCA's network blocking
    try:
        from ..utils.network_protect import _patch_httpx_keepalive

        _patch_httpx_keepalive()
        results["httpx_keepalive"] = True
        log.info("HTTP keepalive patch active (survive CSCA idle timeout)")
    except Exception as exc:
        results["httpx_keepalive"] = False
        log.debug("HTTP keepalive patch skipped: %s", exc)

    active = sum(1 for v in results.values() if v)
    total = len(results)
    log.info("CSCA protections: %d/%d active", active, total)

    return results


def cleanup_csca_protections() -> None:
    """Remove protections before normal shutdown.

    MUST be called before sys.exit() if terminate protection was applied,
    otherwise exiting may trigger BSOD (critical process flag).
    """
    if sys.platform != "win32":
        return

    try:
        from .terminate_protect import remove_terminate_protection

        remove_terminate_protection()
    except Exception:
        pass

    try:
        from .process_hide import stop_process_checker_spoofer

        stop_process_checker_spoofer()
    except Exception:
        pass

    try:
        from .window_cloak import remove_cbt_hook

        remove_cbt_hook()
    except Exception:
        pass

    log.info("CSCA protections cleaned up")
