"""Executable skills endpoints — event hook dispatching and tool invocation."""

from __future__ import annotations

import logging
from typing import Any

from fastapi import APIRouter
from pydantic import BaseModel, Field

router = APIRouter()
logger = logging.getLogger(__name__)


class HookExecuteRequest(BaseModel):
    """Request to execute a skill event hook."""
    tool_name: str = Field(..., max_length=64, description="Tool name to invoke")
    args: dict[str, str] = Field(default_factory=dict, description="Arguments to pass to the tool")
    workspace_path: str = Field(default="", description="Workspace root path")


@router.post("/hooks/execute")
async def execute_hook(request: HookExecuteRequest) -> dict[str, Any]:
    """Execute a skill event hook by invoking the named tool.

    The tool is dispatched via the shared tool_implementations module,
    falling back to the MCP bridge for non-built-in tools.
    """
    from dsc_api.services import tool_implementations

    tool_name = request.tool_name
    workspace = request.workspace_path
    args = request.args

    logger.info("Skill hook executing tool '%s' with args=%s", tool_name, list(args.keys()))

    try:
        # Map common hook tool names to tool_implementations functions
        if tool_name == "run_scan":
            result = await tool_implementations.run_scan(
                workspace, args.get("target_path", workspace)
            )
        elif tool_name == "run_command":
            result = await tool_implementations.run_command(
                workspace, args.get("command", "echo 'no command specified'")
            )
        elif tool_name == "run_tests":
            result = await tool_implementations.run_tests(workspace)
        elif tool_name == "search_files":
            result = await tool_implementations.search_files(
                workspace, args.get("pattern", ""), args.get("file_pattern", "")
            )
        elif tool_name == "read_file":
            result = await tool_implementations.read_file(
                workspace, args.get("file_path", "")
            )
        elif tool_name == "get_diagnostics":
            result = await tool_implementations.get_diagnostics(workspace)
        else:
            # Non-built-in tool — log that it would need MCP dispatch
            # (MCP dispatch requires an active SSE session, which hooks don't have)
            logger.info("Skill hook: tool '%s' is not a built-in — skipping (MCP dispatch requires active session)", tool_name)
            return {
                "status": "skipped",
                "tool_name": tool_name,
                "reason": "Non-built-in tools require an active chat session for MCP dispatch",
            }

        return {
            "status": "ok",
            "tool_name": tool_name,
            "output": result[:4000] if isinstance(result, str) else str(result)[:4000],
        }

    except Exception as exc:
        logger.warning("Skill hook execution failed for tool '%s': %s", tool_name, exc)
        return {
            "status": "error",
            "tool_name": tool_name,
            "error": str(exc)[:1000],
        }
