"""
Endpoint detection - find API endpoints in backend code
"""
import re
from pathlib import Path
from typing import List, Dict


# Common endpoint patterns
ENDPOINT_PATTERNS = [
    # Python Flask @app.route
    (r'@app\.route\(["\']([^"\']+)["\'](?:.*?methods\s*=\s*\[["\']([^"\']+)["\'])?', 'python_flask_route'),
    
    # Python Flask/FastAPI method decorators
    (r'@app\.(get|post|put|delete|patch)\(["\']([^"\']+)["\']', 'python'),
    (r'@router\.(get|post|put|delete|patch)\(["\']([^"\']+)["\']', 'python'),
    
    # JavaScript/TypeScript Express
    (r'app\.(get|post|put|delete|patch)\(["\']([^"\']+)["\']', 'javascript'),
    (r'router\.(get|post|put|delete|patch)\(["\']([^"\']+)["\']', 'javascript'),
    
    # Go
    (r'(GET|POST|PUT|DELETE|PATCH)\(["\']([^"\']+)["\']', 'go'),
    
    # Java Spring
    (r'@(GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping)\(["\']([^"\']+)["\']', 'java'),
]


def find_endpoints(file_path: Path, content: str) -> List[Dict]:
    """
    Find API endpoints in file content
    
    Args:
        file_path: Path to file
        content: File content
        
    Returns:
        List of endpoint dictionaries
    """
    endpoints = []
    
    for pattern, language in ENDPOINT_PATTERNS:
        matches = re.finditer(pattern, content, re.IGNORECASE | re.DOTALL)
        
        for match in matches:
            # Handle Flask @app.route specially
            if language == 'python_flask_route':
                path = match.group(1)
                method = match.group(2) if match.group(2) else 'GET'  # Default to GET
                method = method.upper()
            else:
                method = match.group(1).upper()
                path = match.group(2)
            
            # Get line number
            line_num = content[:match.start()].count('\n') + 1
            
            endpoints.append({
                "method": method,
                "path": path,
                "file": str(file_path),
                "line": line_num,
                "language": language.replace('_flask_route', ''),
                "type": "endpoint"
            })
    
    return endpoints
