#!/usr/bin/env python3
"""
HEPHAESTUS Self-Validation Hook
Implements Phase 2: Mandatory Self-Validation from Claude Collective v9.4.2

This hook enforces the mandatory static analysis cycle after any code modification.
"""

import json
import os
import subprocess
import sys
from pathlib import Path


def get_static_analysis_command(file_path: str) -> list[str] | None:
    """Determine the appropriate static analysis command based on file extension."""
    file_ext = Path(file_path).suffix.lower()

    commands = {
        ".py": ["python", "-m", "py_compile", file_path],
        ".js": ["node", "-c", file_path],
        ".ts": ["npx", "tsc", "--noEmit", file_path],
        ".jsx": ["node", "-c", file_path],
        ".tsx": ["npx", "tsc", "--noEmit", file_path],
        ".rs": ["cargo", "check", "--manifest-path", "Cargo.toml"],
        ".go": ["go", "build", "-o", "/dev/null", file_path],
        ".java": ["javac", "-cp", ".", file_path],
        ".cpp": ["g++", "-fsyntax-only", file_path],
        ".c": ["gcc", "-fsyntax-only", file_path],
    }

    return commands.get(file_ext)


def run_linter(file_path: str) -> tuple[bool, str]:
    """Run appropriate linter based on file extension."""
    file_ext = Path(file_path).suffix.lower()

    linters = {
        ".py": ["ruff", "check", "--fix", file_path],
        ".js": ["eslint", "--fix", file_path],
        ".ts": ["eslint", "--fix", file_path],
        ".jsx": ["eslint", "--fix", file_path],
        ".tsx": ["eslint", "--fix", file_path],
    }

    linter_cmd = linters.get(file_ext)
    if linter_cmd:
        try:
            result = subprocess.run(linter_cmd, capture_output=True, text=True)
            return result.returncode == 0, result.stderr
        except FileNotFoundError:
            return True, f"Linter not found for {file_ext}"

    return True, "No linter available"


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_input = input_data.get("tool_input", {})

    # Only validate code files
    file_path = tool_input.get("file_path", "")
    if not file_path:
        sys.exit(0)

    # Skip non-code files
    code_extensions = {
        ".py",
        ".js",
        ".ts",
        ".jsx",
        ".tsx",
        ".rs",
        ".go",
        ".java",
        ".cpp",
        ".c",
    }
    if Path(file_path).suffix.lower() not in code_extensions:
        sys.exit(0)

    # Skip test files and configuration files
    skip_patterns = ["test", "spec", ".config", ".eslintrc", "package.json"]
    if any(pattern in file_path.lower() for pattern in skip_patterns):
        sys.exit(0)

    print(f"🔧 HEPHAESTUS: Running mandatory self-validation on {file_path}")

    # Phase 2: Mandatory Self-Validation (Static Analysis)
    static_cmd = get_static_analysis_command(file_path)
    if static_cmd:
        try:
            result = subprocess.run(
                static_cmd, capture_output=True, text=True, cwd=os.getcwd()
            )
            if result.returncode != 0:
                error_msg = f"Static analysis failed for {file_path}:\n{result.stderr}"
                print(error_msg, file=sys.stderr)

                # Return structured feedback for automated self-correction
                output = {
                    "decision": "block",
                    "reason": f"HEPHAESTUS Protocol Violation: Static analysis failed. \
                    Please fix the following errors and re-run validation: \
                    \n\n{result.stderr}\n\nThis is mandatory before task completion.",
                }
                print(json.dumps(output))
                sys.exit(0)
        except FileNotFoundError:
            print(f"Warning: Static analysis tool not found for {file_path}")

    # Run linter if available
    linter_success, linter_output = run_linter(file_path)
    if not linter_success:
        print(f"Linter warnings for {file_path}: {linter_output}")

    print(f"✅ HEPHAESTUS: Static validation passed for {file_path}")
    sys.exit(0)


if __name__ == "__main__":
    main()
