#!/usr/bin/env python3
"""
FlyDocs Hook: post-edit.py
Triggered: After Edit or Write tool completes
Purpose: Auto-format code after agent edits

Exit codes:
  0 - Success (optional JSON output parsed)
  2 - Blocking error (stderr shown to Claude)
  Other - Non-blocking error (shown in verbose mode)
"""

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


def get_file_extension(file_path: str) -> str:
    """Extract file extension from path."""
    return Path(file_path).suffix.lstrip('.')


def format_file(file_path: str, ext: str) -> None:
    """Auto-format file based on extension (non-blocking)."""
    try:
        if ext in ('ts', 'tsx', 'js', 'jsx', 'json', 'md'):
            # Check if package.json exists and npx is available
            if Path('package.json').exists():
                subprocess.run(
                    ['npx', 'prettier', '--write', file_path],
                    capture_output=True,
                    timeout=30
                )
        elif ext == 'py':
            # Use black if available
            subprocess.run(
                ['black', '--quiet', file_path],
                capture_output=True,
                timeout=30
            )
    except (subprocess.TimeoutExpired, FileNotFoundError, subprocess.SubprocessError):
        # Non-blocking - silently skip formatting failures
        pass


def main() -> None:
    """Main hook execution."""
    # Read hook input from stdin
    try:
        input_data = json.loads(sys.stdin.read())
    except (json.JSONDecodeError, ValueError):
        input_data = {}

    file_path = input_data.get('tool_input', {}).get('file_path', '')

    # Skip if no file path
    if not file_path:
        print('{}')
        sys.exit(0)

    # Validate file_path is within project directory
    project_dir = os.environ.get('CLAUDE_PROJECT_DIR', os.getcwd())
    try:
        resolved = os.path.realpath(file_path)
        project_resolved = os.path.realpath(project_dir)
        if not resolved.startswith(project_resolved + os.sep) and resolved != project_resolved:
            print('{}')
            sys.exit(0)
    except (OSError, ValueError):
        print('{}')
        sys.exit(0)

    # Get file extension and format
    ext = get_file_extension(file_path)
    format_file(file_path, ext)

    # Return empty object to allow operation
    print('{}')
    sys.exit(0)


if __name__ == '__main__':
    main()
