"""
DSS MCP - Code Analysis Tools
"""
import asyncio
from typing import Dict, Any

# Adjust the import path to find the project_analyzer
# This assumes the script is run from the project root.
from tools.analysis.project_analyzer import analyze_react_project, save_analysis

class Tool:
    """Basic tool definition for MCP"""
    def __init__(self, name: str, description: str, input_schema: Dict[str, Any]):
        self.name = name
        self.description = description
        self.inputSchema = input_schema

# Define the new tool
analyze_project_tool = Tool(
    name="analyze_project",
    description="Analyzes a given project's structure, components, and styles. This is a long-running operation.",
    input_schema={
        "type": "object",
        "properties": {
            "project_path": {
                "type": "string",
                "description": "The absolute path to the project to be analyzed."
            }
        },
        "required": ["project_path"]
    }
)

class AnalysisTools:
    """
    A wrapper class for analysis-related tools.
    """
    def __init__(self, user_id: str = None):
        self.user_id = user_id

    async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        if tool_name == "analyze_project":
            return await self.analyze_project(arguments.get("project_path"))
        else:
            return {"error": f"Analysis tool '{tool_name}' not found."}

    async def analyze_project(self, project_path: str) -> Dict[str, Any]:
        """
        Triggers the analysis of a project.
        """
        if not project_path:
            return {"error": "project_path is a required argument."}

        try:
            # This is a potentially long-running task.
            # In a real scenario, this should be offloaded to a background worker.
            # For now, we run it asynchronously.
            loop = asyncio.get_event_loop()
            
            # Run the analysis in a separate thread to avoid blocking the event loop
            analysis_data = await loop.run_in_executor(
                None, analyze_react_project, project_path
            )
            
            # Save the analysis data
            await loop.run_in_executor(
                None, save_analysis, project_path, analysis_data
            )

            return {
                "status": "success",
                "message": f"Analysis complete for project at {project_path}.",
                "graph_nodes": len(analysis_data.get("nodes", [])),
                "graph_edges": len(analysis_data.get("links", []))
            }
        except Exception as e:
            return {"error": f"An error occurred during project analysis: {str(e)}"}

# A list of all tools in this module
ANALYSIS_TOOLS = [
    analyze_project_tool
]
