"""Validation API endpoints — protocol compliance checking.

Reuses the existing validator runner to execute validation rules against
MCP servers and return structured results.
"""

from __future__ import annotations

from aiohttp import web

validate_routes = web.RouteTableDef()


@validate_routes.get("/api/validate/{server}")
async def get_validation(request: web.Request) -> web.Response:
    """Get most recent validation results for a server."""
    server = request.match_info["server"]

    # Run validation on demand (no persistent storage for validation results yet)
    return await _run_validation_for(server)


@validate_routes.post("/api/validate/{server}/run")
async def run_validation(request: web.Request) -> web.Response:
    """Trigger a new validation run against a server."""
    server = request.match_info["server"]
    return await _run_validation_for(server)


async def _run_validation_for(server_name: str) -> web.Response:
    """Execute validator against a server and return structured results."""
    try:
        from pathlib import Path

        from hatchdx.utils.config import load_config, resolve_server_command
        from hatchdx.validator.runner import run_validation_with_simulator
        from hatchdx.harness.simulator import StdioSimulator

        config = load_config()

        if config.server_name != server_name:
            return web.json_response(
                {"error": f"Server '{server_name}' not found in config"},
                status=404,
            )

        project_dir = Path.cwd()
        cmd = resolve_server_command(config.server_command.split(), project_dir)
        async with StdioSimulator(cmd, timeout=10.0, cwd=str(project_dir)) as sim:
            report = await run_validation_with_simulator(sim, server_name=server_name)

        total = len(report.results)
        passed = report.passed_count
        failed = report.failed_count

        rules = []
        for r in report.results:
            # Collect affected tools
            affected = [r.tool_name] if r.tool_name else []

            status = "pass" if r.passed else ("warn" if r.rule.severity == "warning" else "fail")

            rules.append({
                "id": f"{r.rule.category}.{r.rule.name}",
                "category": r.rule.category,
                "name": r.rule.name,
                "description": r.rule.description,
                "status": status,
                "affected_tools": affected,
                "message": r.message,
                "severity": r.rule.severity,
            })

        score = round(passed / total * 100) if total > 0 else 0

        return web.json_response({
            "server": server_name,
            "timestamp": report.timestamp.isoformat(),
            "score": score,
            "total_rules": total,
            "passed": passed,
            "failed": failed - report.warning_count,
            "warned": report.warning_count,
            "rules": rules,
        })

    except ImportError as e:
        return web.json_response(
            {"error": f"Validator not available: {e}"},
            status=501,
        )
    except Exception as e:
        return web.json_response(
            {"error": f"Validation failed: {e}"},
            status=500,
        )
