#!/usr/bin/env python3
"""Hook to block Claude Code from accessing forbidden files."""

import json
import sys

# Files that Claude should not be allowed to read or modify
FORBIDDEN_FILES = [
    ".env",
    "settings.local.json",
    "glm.settings.local.json",
]


def is_forbidden_file(file_path: str) -> bool:
    """Check if a file path matches any forbidden file pattern."""
    if not file_path:
        return False

    # Normalize path separators
    normalized_path = file_path.replace("\\", "/")

    for forbidden in FORBIDDEN_FILES:
        # Check if the path ends with the forbidden file name
        if normalized_path.endswith(forbidden):
            return True
        # Check if forbidden file appears as a path component
        if f"/{forbidden}" in normalized_path or normalized_path == forbidden:
            return True

    return False


def main():
    # Read hook input from stdin
    try:
        input_data = json.load(sys.stdin)
    except json.JSONDecodeError as e:
        # Log error to stderr for debugging
        print(f"[block_forbidden_files] JSON decode error: {e}", file=sys.stderr)
        sys.exit(0)

    tool_name = input_data.get("tool_name", "")
    tool_input = input_data.get("tool_input", {})

    # Check file_path for Read, Edit, Write tools
    file_path = tool_input.get("file_path", "")

    if is_forbidden_file(file_path):
        output = {
            "hookSpecificOutput": {
                "hookEventName": "PreToolUse",
                "permissionDecision": "deny",
                "permissionDecisionReason": f"Access to '{file_path}' is blocked. This file contains sensitive configuration data."
            }
        }
        print(json.dumps(output))
        sys.exit(0)

    # Allow by default
    sys.exit(0)


if __name__ == "__main__":
    main()
