"""
Digital Optimus — Safe Brain Host Bootstrap (Migration Recovery Contract)

Responsibilities:
1. Enforce localhost-only binding (BRAIN_HOST_BIND_ADDRESS = 127.0.0.1).
2. Enforce TEITAN observation-only isolation and block C:\\TEITAN_Lab imports.
3. Prevent activation of app.remediation.self_repair (live_shadow_hook) via
   sys.meta_path import contract so brain_host_tls.py cleanly resolves
   dispatch_live_shadow_hook = None without modifying protected files.
4. Provide a safe no-op contract module for app.system_health.runtime_monitor
   so start_continuous_health_monitor() does not spawn unauthorized background
   monitors or self-repair triggers.
5. Verify OPENAI_API_KEY is present in process memory (without logging its value).
6. Delegate execution to artifacts/brain_host/brain_host_tls.py as __main__.
"""

import importlib.abc
import importlib.machinery
import os
import runpy
import sys
import types

REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
BRAIN_HOST_SCRIPT = os.path.join(REPO_ROOT, "artifacts", "brain_host", "brain_host_tls.py")


class SafeBootstrapImportGuard(importlib.abc.MetaPathFinder):
    """Verifiable import blocker for self-repair and TEITAN modules."""

    BLOCKED_PREFIXES = (
        "app.remediation.self_repair",
        "teitan",
        "ar13z",
    )

    def find_spec(self, fullname: str, path=None, target=None):
        lowered = (fullname or "").lower()
        for prefix in self.BLOCKED_PREFIXES:
            if lowered == prefix or lowered.startswith(prefix + "."):
                raise ImportError(
                    f"[SAFE_BOOTSTRAP_CONTRACT] Import blocked by policy: {fullname}"
                )
        return None


def _install_safe_runtime_monitor_stub() -> None:
    """Register a contract-compliant no-op stub for app.system_health.runtime_monitor."""
    import app
    import app.system_health

    mod_name = "app.system_health.runtime_monitor"
    stub = types.ModuleType(mod_name)
    stub.__file__ = os.path.join(REPO_ROOT, "app", "system_health", "runtime_monitor.py")
    stub.__doc__ = "Safe Bootstrap Contract Stub — ContinuousHealthMonitor disabled."
    stub.SAFE_CONTRACT_NEUTRALIZED = True

    def start_continuous_health_monitor(*args, **kwargs):
        print(
            "[SAFE_BOOTSTRAP] ContinuousHealthMonitor neutralized by safe startup contract.",
            flush=True,
        )
        return None

    def stop_continuous_health_monitor(*args, **kwargs):
        return None

    stub.start_continuous_health_monitor = start_continuous_health_monitor
    stub.stop_continuous_health_monitor = stop_continuous_health_monitor
    sys.modules[mod_name] = stub
    setattr(app.system_health, "runtime_monitor", stub)


def _enforce_environment_contracts() -> None:
    """Enforce localhost binding, TEITAN isolation, and sys.path hygiene."""
    bind_addr = os.environ.get("BRAIN_HOST_BIND_ADDRESS", "127.0.0.1").strip()
    if bind_addr != "127.0.0.1":
        print(
            f"[SAFE_BOOTSTRAP] Overriding non-loopback BRAIN_HOST_BIND_ADDRESS={bind_addr!r} -> '127.0.0.1'",
            flush=True,
        )
    os.environ["BRAIN_HOST_BIND_ADDRESS"] = "127.0.0.1"
    os.environ["TEITAN_OBSERVATION_ONLY"] = "1"
    os.environ["OPTIMUS_SAFE_BOOTSTRAP"] = "1"
    os.environ["OPTIMUS_DISABLE_SELF_REPAIR"] = "1"
    os.environ["OPTIMUS_DISABLE_RUNTIME_MONITOR"] = "1"

    # Strip any sys.path entries pointing to C:\TEITAN_Lab
    sys.path[:] = [
        p for p in sys.path if "teitan_lab" not in os.path.abspath(p).lower()
    ]
    if REPO_ROOT not in sys.path:
        sys.path.insert(0, REPO_ROOT)

    # Install meta_path guard at index 0
    if not any(isinstance(f, SafeBootstrapImportGuard) for f in sys.meta_path):
        sys.meta_path.insert(0, SafeBootstrapImportGuard())

    _install_safe_runtime_monitor_stub()


def verify_contracts_only() -> int:
    """Dry-run contract check used by -CheckOnly without starting the server."""
    _enforce_environment_contracts()

    # 1. Verify self_repair import is blocked
    self_repair_blocked = False
    try:
        __import__("app.remediation.self_repair.live_shadow_hook")
    except ImportError:
        self_repair_blocked = True

    # 2. Verify runtime_monitor is stubbed
    import app.system_health.runtime_monitor as rm

    monitor_neutralized = getattr(rm, "SAFE_CONTRACT_NEUTRALIZED", False) is True

    # 3. Verify bind address
    bind_ok = os.environ.get("BRAIN_HOST_BIND_ADDRESS") == "127.0.0.1"

    # 4. Verify OPENAI_API_KEY is present in process environment (never print value)
    api_key = os.environ.get("OPENAI_API_KEY", "")
    key_ok = isinstance(api_key, str) and len(api_key.strip()) > 20 and api_key.startswith("sk-")

    print(
        f"[SAFE_BOOTSTRAP_CHECK] bind_127_0_0_1={bind_ok} "
        f"self_repair_blocked={self_repair_blocked} "
        f"monitor_neutralized={monitor_neutralized} "
        f"openai_key_loaded={key_ok} "
        f"brain_script_exists={os.path.isfile(BRAIN_HOST_SCRIPT)}",
        flush=True,
    )
    if bind_ok and self_repair_blocked and monitor_neutralized and key_ok and os.path.isfile(BRAIN_HOST_SCRIPT):
        return 0
    return 2


def main() -> int:
    _enforce_environment_contracts()
    if "--verify-contracts-only" in sys.argv:
        return verify_contracts_only()

    if not os.path.isfile(BRAIN_HOST_SCRIPT):
        print(f"[SAFE_BOOTSTRAP] ERROR: Missing {BRAIN_HOST_SCRIPT}", file=sys.stderr, flush=True)
        return 1

    os.chdir(REPO_ROOT)
    sys.argv = [BRAIN_HOST_SCRIPT] + [a for a in sys.argv[1:] if a != "--verify-contracts-only"]
    print(
        f"[SAFE_BOOTSTRAP] Launching Brain Host via safe contract wrapper on 127.0.0.1:8443",
        flush=True,
    )
    runpy.run_path(BRAIN_HOST_SCRIPT, run_name="__main__")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
