"""
Chromium Source Code MCP Server
This server provides access to Chromium source code that is otherwise difficult to fetch directly.
"""
from typing import Optional
import httpx
from mcp.server.fastmcp import FastMCP
import re

# Initialize FastMCP server
mcp = FastMCP("Chromium Source Server")


def main():
    """Main entry point for the Chromium Source MCP Server."""
    # Run the MCP server with stdio transport
    mcp.run(transport="stdio")

def extract_chromium_file_path(url: str) -> Optional[str]:
    """
    Extract file path from Chromium source URL.
    Example: https://source.chromium.org/chromium/chromium/src/+/main:chrome/app/chrome_main.cc
    """
    import re
    
    # Pattern to match Chromium source URLs - more comprehensive
    # This handles both simple branch names (like 'main') and refs (like 'refs/heads/main')
    pattern = r'https://source\.chromium\.org/[^/]+/[^/]+/[^/]+/src/\+/(?:refs/heads/)?([^:]+):(.+)'
    match = re.search(pattern, url)
    if match:
        return match.group(2)  # Return the file path part (group 2)
    
    # If the above pattern doesn't match, try a more general approach
    if 'source.chromium.org' in url and '/+/' in url and ':' in url:
        try:
            # Find the part after '/+/' and split by ':'
            after_plus = url.split('/+/')[1]
            parts = after_plus.split(':', 1)  # Split only on first colon
            if len(parts) == 2:
                return parts[1]  # Return the file path part
        except:
            pass
    
    return None

async def fetch_chromium_source_file(file_path: str, branch: str = "main") -> str:
    """
    Fetch Chromium source file using the raw content API.
    """
    # Construct the raw file URL for Chromium source
    raw_url = f"https://chromium.googlesource.com/chromium/src/+/refs/heads/{branch}/{file_path}?format=TEXT"
    
    async with httpx.AsyncClient() as client:
        try:
            response = await client.get(raw_url, timeout=30.0)
            if response.status_code == 200:
                # Chromium returns base64 encoded content
                import base64
                try:
                    decoded_content = base64.b64decode(response.text).decode('utf-8')
                    return decoded_content
                except Exception:
                    # If not base64 encoded, return as is
                    return response.text
            else:
                return f"Error: Failed to fetch file '{file_path}' from branch '{branch}'. Status code: {response.status_code}"
        except httpx.RequestError as e:
            return f"Error: Failed to fetch file '{file_path}' from branch '{branch}'. Request error: {str(e)}"
        except Exception as e:
            return f"Error: Failed to fetch file '{file_path}' from branch '{branch}'. Unexpected error: {str(e)}"

async def fetch_chromium_source_by_url(url: str) -> str:
    """
    Fetch Chromium source file by URL, extracting the path from the URL.
    """
    file_path = extract_chromium_file_path(url)
    if not file_path:
        return "Error: Invalid Chromium source URL format. Expected format: https://source.chromium.org/project/repo/src/+/branch:file/path"
    
    # Extract branch from URL (default is main)
    branch_match = re.search(r'https://source\.chromium\.org/[^/]+/[^/]+/[^/]+/src/\+/(?:refs/heads/)?([^:]+):', url)
    branch = branch_match.group(1) if branch_match else "main"
    
    return await fetch_chromium_source_file(file_path, branch)

@mcp.tool()
async def get_chromium_file(file_path: str, branch: str = "main") -> str:
    """
    Get a specific Chromium source file by file path and branch.
    
    Args:
        file_path: Path to the file in the Chromium repository (e.g., 'chrome/app/chrome_main.cc')
        branch: Branch name (default is 'main', can be 'main', 'refs/heads/main', etc.)
    """
    return await fetch_chromium_source_file(file_path, branch)

@mcp.tool()
async def get_chromium_file_from_url(url: str) -> str:
    """
    Get a Chromium source file by providing the source.chromium.org URL.
    
    Args:
        url: URL from source.chromium.org (e.g., 'https://source.chromium.org/chromium/chromium/src/+/main:chrome/app/chrome_main.cc')
    """
    return await fetch_chromium_source_by_url(url)

if __name__ == "__main__":
    mcp.run(transport="stdio")