"""SessionStart hook: verify economy hook infrastructure integrity.
Emits visible systemMessage if any required component missing.
Stays silent if everything OK."""
import json
import os
import shutil
import sys
from pathlib import Path

try:
    sys.stdin.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass


REQUIRED_HOOKS = [
    "skill-marker.py",
    "skill-check.py",
    "economy-mode.py",
    "economy-self-check.py",
    "economy-state-guard.py",
]
OPTIONAL_HOOKS = [
    "economy-verifier.py",
    "economy-postcompact.py",
]


def main() -> None:
    issues = []
    home = Path(os.environ.get("USERPROFILE") or os.environ.get("HOME") or "")
    if not home or not home.exists():
        return

    hooks_dir = home / ".claude" / "hooks"

    for f in REQUIRED_HOOKS:
        if not (hooks_dir / f).is_file():
            issues.append(f"ERROR: required hook {f} missing")

    for f in OPTIONAL_HOOKS:
        if not (hooks_dir / f).is_file():
            issues.append(f"WARN: optional hook {f} missing — feature disabled")

    if shutil.which("python") is None:
        issues.append("CRITICAL: 'python' not on PATH — ALL hooks broken")

    settings_path = home / ".claude" / "settings.json"
    if not settings_path.is_file():
        issues.append("CRITICAL: settings.json missing")
    else:
        try:
            with open(settings_path, encoding="utf-8") as f:
                settings = json.load(f)
            hooks_block = settings.get("hooks", {})
            ups_handlers = hooks_block.get("UserPromptSubmit", [])
            registered = any(
                "economy-mode.py" in c.get("command", "")
                for h in ups_handlers
                for c in h.get("hooks", [])
            )
            if not registered:
                issues.append("ERROR: economy-mode.py not registered in UserPromptSubmit")
        except Exception as e:
            issues.append(f"CRITICAL: settings.json broken: {e}")

    if issues:
        msg = "Economy hook self-check FAILED:\n" + "\n".join(f"  - {i}" for i in issues)
        print(json.dumps({"systemMessage": msg}, ensure_ascii=True))


if __name__ == "__main__":
    main()
