"""
MCP Tool Definitions and Handlers

Wraps existing Rohkun CLI functionality without modifying it.
"""
import json
from pathlib import Path
from typing import Dict, Any, List


def get_tools() -> List[Dict[str, Any]]:
    """Return list of available MCP tools"""
    return [
        {
            "name": "analyze_codebase",
            "description": """Analyze codebase to discover API endpoints, API calls, connections, and architecture.

TRIGGER PHRASES (use this tool when user says):
- "what endpoints", "list endpoints", "show endpoints"
- "API structure", "codebase architecture", "code structure"  
- "what APIs exist", "what routes are there"
- "API connections", "frontend-backend mapping"
- "analyze this project", "scan the codebase"
- "understand the codebase", "how is this organized"
- "find API calls", "map dependencies"
- "codebase overview", "project structure"

AUTOMATICALLY PROVIDES:
- Complete endpoint inventory
- API call locations
- Connection mapping
- 3D visualization
- Change tracking snapshot

USE THIS FIRST when user asks about codebase structure or APIs.""",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Project directory path. Use '.' for current directory. Defaults to current directory if not specified.",
                        "default": "."
                    }
                }
            }
        },
        {
            "name": "check_impact",
            "description": """Calculate impact analysis (blast radius) for code changes.

TRIGGER PHRASES:
- "what would break", "what would be affected"
- "impact of changing", "if I change this"
- "what depends on", "dependencies of"
- "blast radius", "ripple effect"
- "what uses this", "what calls this"

EXAMPLES:
- "What would break if I change GET /api/users?"
- "What depends on this endpoint?"
- "Show me the impact of removing this function"

Target format: 'GET:/api/users' or 'POST:/api/users'""",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Project directory path",
                        "default": "."
                    },
                    "target": {
                        "type": "string",
                        "description": "Target to analyze (e.g., 'GET:/api/users')"
                    }
                },
                "required": ["target"]
            }
        },
        {
            "name": "show_changes",
            "description": """Compare current snapshot with previous snapshot to show what changed.

TRIGGER PHRASES:
- "what changed", "recent changes", "what's new"
- "since last", "since yesterday", "since last scan"
- "compare", "differences", "what's different"
- "what was added", "what was removed"

AUTOMATICALLY compares latest with previous snapshot.""",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Project directory path",
                        "default": "."
                    }
                }
            }
        },
        {
            "name": "visualize_architecture",
            "description": """Generate and open interactive 3D visualization of codebase architecture.

TRIGGER PHRASES:
- "show visualization", "visualize", "show graph"
- "architecture diagram", "code graph"
- "show me how it's connected"

Opens visualization in browser automatically.""",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Project directory path",
                        "default": "."
                    }
                }
            }
        },
        {
            "name": "list_snapshots",
            "description": """List all snapshots for a project with metadata.

Shows scan history with drift scores and status.""",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "project_path": {
                        "type": "string",
                        "description": "Project directory path",
                        "default": "."
                    }
                }
            }
        }
    ]


def handle_tool_call(tool_name: str, params: Dict[str, Any]) -> Dict[str, Any]:
    """Route tool calls to appropriate handlers"""
    handlers = {
        "analyze_codebase": handle_analyze_codebase,
        "check_impact": handle_check_impact,
        "show_changes": handle_show_changes,
        "visualize_architecture": handle_visualize_architecture,
        "list_snapshots": handle_list_snapshots
    }
    
    handler = handlers.get(tool_name)
    if not handler:
        raise ValueError(f"Unknown tool: {tool_name}")
    
    return handler(params)


def handle_analyze_codebase(params: Dict[str, Any]) -> Dict[str, Any]:
    """Run code analysis - wraps existing CLI functionality"""
    from ..analyzer.scanner import scan_project
    from ..report.formatter import format_report, save_report
    from ..snapshot.tracker import SnapshotTracker
    from ..visualization.generator import generate_visualization
    from ..visualization.server import start_visualization_server
    from ..auth import authorize_scan
    from ..config import Config
    from ..utils.file_utils import estimate_project_size
    
    project_path = Path(params.get("project_path", ".")).resolve()
    
    # Get API key
    config = Config(project_path)
    api_key = config.get_api_key()
    
    if not api_key:
        return {
            "content": [{
                "type": "text",
                "text": json.dumps({
                    "error": "No API key found",
                    "message": "Set your API key with: rohkun config --api-key YOUR_KEY",
                    "get_key_url": "https://rohkun.com/dashboard"
                })
            }]
        }
    
    # Estimate size and authorize
    size_info = estimate_project_size(project_path)
    auth_result = authorize_scan(
        api_key=api_key,
        project_name=project_path.name,
        estimated_files=size_info['file_count']
    )
    
    if not auth_result.authorized:
        return {
            "content": [{
                "type": "text",
                "text": json.dumps({
                    "error": "Authorization failed",
                    "reason": auth_result.reason,
                    "message": auth_result.message,
                    "credits_remaining": auth_result.credits_remaining
                })
            }]
        }
    
    # Run analysis
    results = scan_project(project_path)
    report = format_report(results, project_path)
    report_file = save_report(report, project_path)
    
    # Save snapshot
    tracker = SnapshotTracker(project_path)
    project_info = tracker.get_or_create_project()
    snapshot = tracker.save_snapshot(results, report_file.name)
    
    # Generate visualization
    viz_file = generate_visualization(report, project_path)
    viz_dir = viz_file.parent
    server_thread, port = start_visualization_server(viz_dir, port=8000)
    
    return {
        "content": [{
            "type": "text",
            "text": json.dumps({
                "report_path": str(report_file),
                "visualization_url": f"http://localhost:{port}",
                "summary": results.get("summary", {}),
                "snapshot": snapshot,
                "project_hash": project_info['project_hash'],
                "credits_remaining": auth_result.credits_remaining
            }, indent=2)
        }]
    }


def handle_check_impact(params: Dict[str, Any]) -> Dict[str, Any]:
    """Calculate blast radius - basic implementation"""
    from ..report.comparison import load_report
    
    project_path = Path(params.get("project_path", ".")).resolve()
    target = params.get("target")
    
    if not target:
        raise ValueError("Target parameter is required")
    
    # Load latest report
    reports_dir = project_path / ".rohkun" / "reports"
    if not reports_dir.exists():
        raise ValueError("No reports found. Run analyze_codebase first.")
    
    report_files = sorted(reports_dir.glob("report_*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
    if not report_files:
        raise ValueError("No reports found. Run analyze_codebase first.")
    
    report = load_report(report_files[0])
    
    # Basic impact analysis
    endpoints = report.get("endpoints", [])
    api_calls = report.get("api_calls", [])
    connections = report.get("connections", [])
    
    # Find target
    target_endpoint = None
    for ep in endpoints:
        ep_id = f"{ep.get('method')}:{ep.get('path')}"
        if ep_id == target:
            target_endpoint = ep
            break
    
    if not target_endpoint:
        return {
            "content": [{
                "type": "text",
                "text": json.dumps({
                    "error": "Target not found",
                    "target": target,
                    "available_endpoints": [f"{ep.get('method')}:{ep.get('path')}" for ep in endpoints[:10]]
                })
            }]
        }
    
    # Find dependents
    affected_calls = [call for call in api_calls if call.get("endpoint") == target]
    affected_files = list(set(call.get("file") for call in affected_calls))
    
    severity = "low"
    if len(affected_calls) > 10:
        severity = "critical"
    elif len(affected_calls) > 5:
        severity = "high"
    elif len(affected_calls) > 2:
        severity = "medium"
    
    return {
        "content": [{
            "type": "text",
            "text": json.dumps({
                "target": target,
                "target_type": "endpoint",
                "target_file": target_endpoint.get("file"),
                "target_line": target_endpoint.get("line"),
                "direct_dependents": len(affected_calls),
                "affected_files": affected_files,
                "severity": severity,
                "impact_description": f"Changing this endpoint would affect {len(affected_calls)} API calls across {len(affected_files)} files"
            }, indent=2)
        }]
    }


def handle_show_changes(params: Dict[str, Any]) -> Dict[str, Any]:
    """Compare snapshots - wraps existing functionality"""
    from ..snapshot.tracker import SnapshotTracker
    from ..report.comparison import load_report, compare_reports
    
    project_path = Path(params.get("project_path", ".")).resolve()
    
    tracker = SnapshotTracker(project_path)
    
    # Get latest and previous reports
    reports_dir = project_path / ".rohkun" / "reports"
    if not reports_dir.exists():
        raise ValueError("No reports found. Run analyze_codebase first.")
    
    report_files = sorted(reports_dir.glob("report_*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
    if len(report_files) < 2:
        return {
            "content": [{
                "type": "text",
                "text": json.dumps({
                    "message": "Only one snapshot exists. Run analyze_codebase again to compare changes.",
                    "snapshots_count": len(report_files)
                })
            }]
        }
    
    current_report = load_report(report_files[0])
    previous_report = load_report(report_files[1])
    
    comparison = compare_reports(current_report, previous_report)
    
    return {
        "content": [{
            "type": "text",
            "text": json.dumps(comparison, indent=2)
        }]
    }


def handle_visualize_architecture(params: Dict[str, Any]) -> Dict[str, Any]:
    """Generate visualization - wraps existing functionality"""
    from ..visualization.generator import generate_visualization
    from ..visualization.server import start_visualization_server
    from ..report.comparison import load_report
    
    project_path = Path(params.get("project_path", ".")).resolve()
    
    # Load latest report
    reports_dir = project_path / ".rohkun" / "reports"
    if not reports_dir.exists():
        raise ValueError("No reports found. Run analyze_codebase first.")
    
    report_files = sorted(reports_dir.glob("report_*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
    if not report_files:
        raise ValueError("No reports found. Run analyze_codebase first.")
    
    report = load_report(report_files[0])
    
    # Generate visualization
    viz_file = generate_visualization(report, project_path)
    viz_dir = viz_file.parent
    server_thread, port = start_visualization_server(viz_dir, port=8000)
    
    return {
        "content": [{
            "type": "text",
            "text": json.dumps({
                "visualization_url": f"http://localhost:{port}",
                "html_path": str(viz_file),
                "message": "Visualization server started. Open the URL in your browser."
            }, indent=2)
        }]
    }


def handle_list_snapshots(params: Dict[str, Any]) -> Dict[str, Any]:
    """List snapshots - wraps existing functionality"""
    from ..snapshot.tracker import SnapshotTracker
    
    project_path = Path(params.get("project_path", ".")).resolve()
    
    tracker = SnapshotTracker(project_path)
    snapshot_summary = tracker.get_snapshot_summary()
    
    # Read snapshot index
    snapshot_index_file = project_path / ".rohkun" / "snapshots" / "snapshot_index.json"
    if not snapshot_index_file.exists():
        return {
            "content": [{
                "type": "text",
                "text": json.dumps({
                    "message": "No snapshots found. Run analyze_codebase first.",
                    "snapshots": []
                })
            }]
        }
    
    with open(snapshot_index_file, 'r') as f:
        index = json.load(f)
    
    return {
        "content": [{
            "type": "text",
            "text": json.dumps({
                "snapshots": index.get("snapshots", []),
                "summary": snapshot_summary
            }, indent=2)
        }]
    }
