#!/usr/bin/env python3
"""
Pre-Tool Verification Hook — minimal passthrough.
Reads stdin only if immediately available (non-blocking).
Always outputs {"continue": true} unless a hard safety rule is violated.
"""
import json
import os
import sys


def _allow():
    sys.stdout.write(json.dumps({"continue": True}) + "\n")
    sys.stdout.flush()


def _block(reason: str):
    sys.stdout.write(json.dumps({"continue": False, "message": reason}) + "\n")
    sys.stdout.flush()


def main():
    # Try to read hook payload from stdin in a truly non-blocking way.
    hook_input: dict = {}
    try:
        import fcntl
        fd = sys.stdin.fileno()
        old_flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_flags | os.O_NONBLOCK)
        try:
            data = sys.stdin.buffer.read(131072)
            if data:
                hook_input = json.loads(data.decode("utf-8", errors="ignore"))
        except (BlockingIOError, OSError, ValueError, json.JSONDecodeError):
            pass
        finally:
            fcntl.fcntl(fd, fcntl.F_SETFL, old_flags)
    except Exception:
        pass  # Any failure → allow by default

    tool = hook_input.get("tool", "")
    args = hook_input.get("args", {})

    if tool == "Bash":
        cmd = args.get("command", "")
        lo = cmd.lower()
        # AIVA server
        if "152.53.201.152" in cmd and any(x in cmd for x in ["ssh","scp","rsync","curl","wget"]):
            _block("AIVA PROTECTION: Cannot target 152.53.201.152")
            return
        # Destructive git
        for pat in ["git push --force","git reset --hard","git clean -f",
                    "git branch -D main","git branch -D master"]:
            if pat in cmd:
                _block(f"Destructive git blocked: {pat}")
                return
        # C: drive + write ops
        c_pats = ["/mnt/c/users","/mnt/c/temp","/mnt/c/windows",".claude-worktrees"]
        w_ops  = ["mkdir","touch","git worktree add","git clone","npm install","pip install"]
        for cp in c_pats:
            if cp in lo and any(w in lo for w in w_ops):
                _block("C: drive write is FORBIDDEN. Use E: drive.")
                return
        # SQLite
        if "sqlite3" in lo:
            _block("SQLite is FORBIDDEN. Use Elestio PostgreSQL.")
            return

    elif tool in ("Write", "Edit"):
        fp = args.get("file_path", "").lower()
        if fp.startswith(("c:\\","c:/","/mnt/c/")):
            _block("C: drive write is FORBIDDEN. Use E: drive.")
            return
        if tool == "Write":
            content = args.get("content", "")
            if fp.endswith(".py") and ("import " + "sqlite3") in content:
                _block("SQLite is FORBIDDEN. Use Elestio PostgreSQL.")
                return

    _allow()


if __name__ == "__main__":
    main()
