#!/usr/bin/env python3
"""
Bash Safety Validator Hook
Validates bash commands for safety and workflow compliance

Prevents potentially dangerous commands while allowing safe development operations.
"""

import json
import re
import sys


def is_dangerous_command(command: str) -> tuple[bool, str]:
    """Check if a command is potentially dangerous."""
    dangerous_patterns = [
        r"\brm\s+-rf\s+/",
        r"\bsudo\s+rm",
        r"\bdd\s+if=",
        r"\bformat\s+",
        r"\bmkfs\.",
        r"\bfdisk\s+",
        r"\bchmod\s+777",
        r"\bchown\s+-R\s+\w+:\w+\s+/",
        r">\s*/etc/",
        r"curl.*\|\s*sh",
        r"wget.*\|\s*sh",
        r"\bkill\s+-9\s+1\b",
        r"\bpkill\s+-9",
        r"\bkillall\s+-9",
    ]

    for pattern in dangerous_patterns:
        if re.search(pattern, command, re.IGNORECASE):
            return True, f"Dangerous pattern detected: {pattern}"

    return False, ""


def is_allowed_command(command: str) -> bool:
    """Check if command is in the allowed workflow patterns."""
    allowed_patterns = [
        r"^git\s+",
        r"^npm\s+(install|test|run|build)",
        r"^yarn\s+(install|test|run|build)",
        r"^python\s+-m\s+(pytest|py_compile)",
        r"^node\s+-c\s+",
        r"^eslint\s+",
        r"^ruff\s+",
        r"^black\s+",
        r"^cargo\s+(check|test|build)",
        r"^go\s+(test|build|vet)",
        r"^mvn\s+(test|compile)",
        r"^gradle\s+(test|build)",
        r"^ls\s+",
        r"^cat\s+",
        r"^grep\s+",
        r"^find\s+",
        r"^mkdir\s+",
        r"^cp\s+",
        r"^mv\s+.*\.(py|js|ts|md|json)$",
    ]

    for pattern in allowed_patterns:
        if re.search(pattern, command, re.IGNORECASE):
            return True

    return False


def analyze_command_intent(command: str) -> tuple[str, str]:
    """Analyze the intent behind the command."""
    if re.search(r"test|spec", command, re.IGNORECASE):
        return "testing", "Running tests - aligns with TDD workflow"

    if re.search(r"lint|check|validate", command, re.IGNORECASE):
        return "validation", "Static analysis - supports HEPHAESTUS protocol"

    if re.search(r"git\s+(add|commit|push)", command, re.IGNORECASE):
        return "version_control", "Version control - normal workflow"

    if re.search(r"build|compile", command, re.IGNORECASE):
        return "build", "Building project - implementation workflow"

    if re.search(r"install|update", command, re.IGNORECASE):
        return "dependency", "Managing dependencies"

    return "general", "General command"


def main() -> None:
    try:
        input_data = json.load(sys.stdin)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
        sys.exit(1)

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

    if tool_name != "Bash":
        sys.exit(0)

    command = tool_input.get("command", "")
    if not command:
        sys.exit(0)

    print(f"🛡️  BASH VALIDATOR: Analyzing command: {command[:50]}...")

    # Check for dangerous commands
    is_dangerous, danger_reason = is_dangerous_command(command)
    if is_dangerous:
        error_msg = f"""
SECURITY VIOLATION: Dangerous command blocked

Command: {command}
Reason: {danger_reason}

This command could cause system damage or data loss.
Please use safer alternatives or manual execution with proper precautions.
"""
        print(error_msg, file=sys.stderr)
        sys.exit(2)  # Block the command

    # Analyze command intent
    intent, description = analyze_command_intent(command)

    # Check if command aligns with workflow
    if not is_allowed_command(command):
        warning_msg = f"""
WORKFLOW WARNING: Unusual command detected

Command: {command}
Intent: {intent} - {description}

This command doesn't match typical Claude Collective workflow patterns.
Consider if this aligns with your current task (coordination vs implementation mode).

Common workflow commands:
- git add/commit/push (version control)
- npm/yarn test (TDD validation)
- eslint/ruff/black (static analysis)
- pytest/npm test (ASTRAEA testing)
"""
        print(warning_msg)

        # Don't block, but provide guidance
        output = {
            "continue": True,
            "reason": f"Unusual command detected. Intent: {description}. \
            Proceed with caution.",
        }
        print(json.dumps(output))
        sys.exit(0)

    print(f"✅ BASH VALIDATOR: Command approved - {description}")
    sys.exit(0)


if __name__ == "__main__":
    main()
