"""Get extraction schema tool (Phase 1)."""

import json

from mcp.types import TextContent, Tool

from maeris_mcp.schemas.registry import SchemaRegistry
from maeris_mcp.types.protocol import OperationType, SchemaResponse


def get_extraction_schema_tool() -> Tool:
    """Return the tool definition for get_extraction_schema."""
    return Tool(
        name="get_extraction_schema",
        description=(
            "Returns a JSON Schema defining what structured data to extract from the codebase. "
            "This is Phase 1 of the schema-first protocol."
        ),
        inputSchema={
            "type": "object",
            "required": ["operation"],
            "properties": {
                "operation": {
                    "type": "string",
                    "description": (
                        "The operation to get schema for: analyze_component, analyze_project, "
                        "generate_docs, search_components, search_functions, find_patterns, extract_apis"
                    ),
                },
                "target_path": {
                    "type": "string",
                    "description": "Optional: specific file or directory path to analyze",
                },
                "query": {
                    "type": "string",
                    "description": "Optional: search query or specific question about the code",
                },
                "scope": {
                    "type": "string",
                    "description": "Optional: scope of analysis - 'file', 'directory', or 'project'",
                },
            },
        },
    )


async def handle_get_extraction_schema(
    registry: SchemaRegistry,
    arguments: dict,
) -> list[TextContent]:
    """Handle the get_extraction_schema tool call."""
    operation = arguments.get("operation")
    if not operation:
        return [TextContent(type="text", text="Error: operation is required")]

    try:
        op_type = OperationType(operation)
    except ValueError:
        return [TextContent(type="text", text=f"Error: invalid operation: {operation}")]

    applicable_schemas = registry.get_for_operation(op_type)
    if not applicable_schemas:
        return [TextContent(type="text", text=f"Error: no schema available for operation: {operation}")]

    # Use the first applicable schema
    schema = applicable_schemas[0]

    # Build response
    response = SchemaResponse(
        schema_id=schema.id,
        schema_=schema.json_schema,
        instructions=schema.instructions,
        required_files=[arguments["target_path"]] if arguments.get("target_path") else None,
    )

    response_json = json.dumps(response.model_dump(by_alias=True, exclude_none=True), indent=2)
    return [TextContent(type="text", text=response_json)]
