"""PreToolUse hook for Read: stop Claude reading files that usually hold credentials.

A second layer behind Read deny rules in settings. It can't see a script that opens
the file itself, so keep real secrets out of the working directory as well.
"""

import json
import posixpath
import sys

SECRET_DIRS = ("/secrets/", "/.ssh/")
SECRET_SUFFIXES = (".pem", ".key", ".pfx", ".p12")
SAFE_NAMES = (".env.example",)


def is_secret(path: str) -> bool:
    path = posixpath.normpath(path.replace("\\", "/"))
    name = posixpath.basename(path)
    if name in SAFE_NAMES:
        return False
    if name == ".env" or name.startswith(".env."):
        return True
    return name.endswith(SECRET_SUFFIXES) or any(d in path + "/" for d in SECRET_DIRS)


def main() -> int:
    event = json.load(sys.stdin)
    path = event.get("tool_input", {}).get("file_path", "")
    if is_secret(path):
        print(
            f"Blocked: {path} may hold credentials, and project policy is not to read them. "
            "If you need a connection setting, ask which environment variable holds it.",
            file=sys.stderr,
        )
        return 2
    return 0


if __name__ == "__main__":
    sys.exit(main())
