#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
PULSE Safety Check Hook
Validates that critical constitutional links and safety markers are present.
Run this before committing or after any refactor of PULSE_OS.md.
"""
import sys
import os
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

# --- Configuration ---
from pulse.core.brain_utils import CONSTITUTION_FILE, load_env as _load_env  # noqa: E402
PULSE_OS_MD = ROOT_DIR / "PULSE_OS.md"
CONSTITUTION_MD = CONSTITUTION_FILE

REQUIRED_MARKERS = [
    "CONSTITUTION.md",
    "PRIME DIRECTIVE",
    "Brain First",
]


def check_safety():
    print("!!! Running PULSE Safety Check ---")

    # Load env so crypto can find PULSE_BRAIN_KEY
    _load_env()

    # Trigger Key Vaulting
    try:
        from pulse.core.pulse_crypto import PulseCrypto
        crypto = PulseCrypto(wipe_env=True)
        # 3. Verify Key Vaulting (Phase 3.5)
        if os.environ.get("PULSE_BRAIN_KEY"):
            print("FAIL: PULSE_BRAIN_KEY is EXPOSED in environment!")
            print("MANDATORY: Use PulseCrypto() to vault the key and clear it from memory.")
            return False
        print("OK: Environment is Vaulted (Secret not exposed).")
    except ImportError as e:
        print(f"WARNING: Skipping Key Vaulting check (Dependency missing: {e})")
        print("  NOTE: The Orchestrator enforces this at boot. Install cryptography for full pre-commit coverage.")
    except Exception as e:
        print(f"FAIL: Crypto Initialization failed: {e}")
        return False

    # 1. Verify Constitution file exists
    if not CONSTITUTION_MD.exists():
        print(f"FAIL: {CONSTITUTION_MD.name} is MISSING!")
        return False
    print("OK: Constitution file exists.")

    # 2. Verify PULSE_OS.md integrity
    if not PULSE_OS_MD.exists():
        print("FAIL: PULSE_OS.md is MISSING!")
        return False

    content = PULSE_OS_MD.read_text(encoding="utf-8")
    missing = []
    for marker in REQUIRED_MARKERS:
        if marker not in content:
            missing.append(marker)

    if missing:
        print("FAIL: PULSE_OS.md is missing critical safety markers:")
        for m in missing:
            print(f"   - {m}")
        print("BLOCKED: Possible Aggressive Refactor Detected. DO NOT COMMIT.")
        return False

    print(f"OK: PULSE_OS.md integrity verified (Markers found: {len(REQUIRED_MARKERS)})")

    print("OK: Safety Check Passed")
    return True


if __name__ == "__main__":
    if not check_safety():
        sys.exit(1)
    sys.exit(0)
