"""AST analysis tools for AI agent integration."""

import json
from langchain_core.tools import tool

from ieum.ast import PythonASTParser, CppASTParser, MFCParser


@tool
def analyze_python_tool(file_path: str) -> str:
    """Analyze a Python file using AST parsing to extract classes, functions, and symbols.

    Args:
        file_path: Path to the Python file to analyze.

    Returns:
        JSON string containing extracted symbols (classes, functions, methods).
    """
    parser = PythonASTParser()
    result = parser.parse_file(file_path)

    if not result.success:
        return f"Error parsing file: {', '.join(result.errors)}"

    # Format output
    output = {
        "file": file_path,
        "language": result.language,
        "symbols_count": len(result.symbols),
        "symbols": []
    }

    for sym in result.symbols[:50]:  # Limit to 50 symbols
        output["symbols"].append({
            "name": sym.name,
            "type": sym.type.value,
            "line": sym.line,
            "parent": sym.parent,
            "signature": sym.signature,
        })

    return json.dumps(output, indent=2, ensure_ascii=False)


@tool
def analyze_cpp_tool(file_path: str) -> str:
    """Analyze a C++ file using AST parsing to extract classes, functions, and symbols.

    Args:
        file_path: Path to the C++ file to analyze (.cpp, .h, .hpp).

    Returns:
        JSON string containing extracted symbols (classes, functions, structs).
    """
    parser = CppASTParser()
    result = parser.parse_file(file_path)

    if not result.success:
        return f"Error parsing file: {', '.join(result.errors)}"

    output = {
        "file": file_path,
        "language": result.language,
        "symbols_count": len(result.symbols),
        "symbols": []
    }

    for sym in result.symbols[:50]:
        output["symbols"].append({
            "name": sym.name,
            "type": sym.type.value,
            "line": sym.line,
            "parent": sym.parent,
            "signature": sym.signature,
        })

    return json.dumps(output, indent=2, ensure_ascii=False)


@tool
def analyze_mfc_tool(file_path: str) -> str:
    """Analyze an MFC (Microsoft Foundation Classes) C++ file.

    Extracts MFC-specific patterns like message maps, dialog classes,
    message handlers, and DDX/DDV bindings.

    Args:
        file_path: Path to the MFC C++ file.

    Returns:
        JSON string containing MFC-specific symbols and patterns.
    """
    parser = MFCParser()
    result = parser.parse_file(file_path)

    if not result.success:
        return f"Error parsing file: {', '.join(result.errors)}"

    output = {
        "file": file_path,
        "language": "mfc",
        "symbols_count": len(result.symbols),
        "mfc_classes": [],
        "message_handlers": [],
        "message_maps": [],
        "other_symbols": []
    }

    for sym in result.symbols:
        sym_data = {
            "name": sym.name,
            "type": sym.type.value,
            "line": sym.line,
        }

        if sym.type.value == "dialog_class":
            output["mfc_classes"].append(sym_data)
        elif sym.type.value == "message_handler":
            output["message_handlers"].append(sym_data)
        elif sym.type.value == "message_map":
            output["message_maps"].append(sym_data)
        else:
            output["other_symbols"].append(sym_data)

    return json.dumps(output, indent=2, ensure_ascii=False)
