"""MCP tool registrations for code reviews."""

from mcp.server.fastmcp import Context


def register_tools(mcp, api_fn):
    @mcp.tool()
    async def submit_review_finding(
        session_id: int,
        perspective: str,
        severity: str,
        category: str,
        file_path: str,
        title: str,
        description: str,
        suggestion: str,
        line_start: int | None = None,
        line_end: int | None = None,
        confidence: float | None = None,
        ctx: Context = None,
    ) -> dict | str:
        """Submit a review finding from a perspective agent.

        Called by spawned Claude agents during code review to report issues they find.
        Validates inputs and inserts into review_findings table.

        Args:
            session_id: The review session this finding belongs to.
            perspective: The perspective key (e.g., 'security', 'maintainability').
            severity: Issue severity — 'critical', 'high', 'medium', 'low', or 'info'.
            category: Standardized category tag for convergence detection.
            file_path: Path to the file with the issue (relative to repo root).
            title: Short summary of the issue.
            description: Detailed explanation of the problem.
            suggestion: Recommended fix or improvement.
            line_start: Starting line number (optional).
            line_end: Ending line number (optional).
            confidence: Confidence level 0.0-1.0 (optional, defaults to 0.8).
        """
        return await api_fn(ctx).submit_review_finding(
            session_id, perspective, severity, category, file_path,
            title, description, suggestion, line_start, line_end, confidence,
        )

    @mcp.tool()
    async def complete_review_perspective(
        session_id: int,
        perspective: str,
        tokens_used: int | None = None,
        ctx: Context = None,
    ) -> dict | str:
        """Mark a perspective agent's review as complete.

        Called by spawned Claude agents when they finish reviewing a PR.
        Updates all findings from this perspective to mark agent_status as completed.

        Args:
            session_id: The review session ID.
            perspective: The perspective key (e.g., 'security').
            tokens_used: Number of tokens consumed by this agent (optional).
        """
        return await api_fn(ctx).complete_review_perspective(session_id, perspective, tokens_used)

    @mcp.tool()
    async def create_review_session(
        project_id: str,
        task_id: int,
        perspectives: list[str] | None = None,
        ctx: Context = None,
    ) -> dict | str:
        """Create a new code review session for a task.

        Validates the task exists and has a PR URL, then creates a review session.
        If perspectives are not provided, uses default perspectives.

        Args:
            project_id: The project this review belongs to (repo name).
            task_id: The task ID to review (must have pr_url set).
            perspectives: List of perspective keys to use (optional, defaults to ['security', 'maintainability', 'architecture']).
        """
        return await api_fn(ctx).create_review_session(project_id, task_id, perspectives)

    @mcp.tool()
    async def get_review_session(session_id: int, ctx: Context = None) -> dict | str:
        """Get a review session with all findings grouped by perspective and convergences.

        Returns comprehensive session data including findings organized by perspective,
        agent statuses, and computed convergences.

        Args:
            session_id: The review session ID.
        """
        return await api_fn(ctx).get_review_session(session_id)

    @mcp.tool()
    async def list_review_sessions(
        project_id: str,
        status: str | None = None,
        ctx: Context = None,
    ) -> list[dict] | str:
        """List review sessions for a project, optionally filtered by status.

        Args:
            project_id: The project to list reviews for (repo name).
            status: Filter by status ('pending', 'in_progress', 'completed', 'failed', 'cancelled'). Omit to show all.
        """
        return await api_fn(ctx).list_review_sessions(project_id, status)

    @mcp.tool()
    async def cancel_review_session(session_id: int, ctx: Context = None) -> dict | str:
        """Cancel an in-progress review session.

        Sets the session status to 'cancelled' if currently pending or in_progress.

        Args:
            session_id: The review session ID to cancel.
        """
        return await api_fn(ctx).cancel_review_session(session_id)

    @mcp.tool()
    async def advance_review_pipeline(session_id: int, ctx: Context = None) -> dict | str:
        """Advance the review pipeline to the next stage if ready.

        Idempotent — safe to call multiple times. Checks whether all conditions
        for the current stage are met and moves the pipeline forward if so.

        Returns a dict with 'advanced' (bool), 'from_stage', 'to_stage', and
        optionally 'reason' (when not advanced) or 'tasks_created' (when fix tasks
        were generated).

        Args:
            session_id: The review session ID.
        """
        return await api_fn(ctx).advance_pipeline(session_id)

    @mcp.tool()
    async def get_pipeline_status(session_id: int, ctx: Context = None) -> dict | str:
        """Get detailed pipeline status for a review session.

        Returns a structured breakdown of each pipeline stage (reviewing, fixing,
        verifying, complete) with counts and task statuses.

        Args:
            session_id: The review session ID.
        """
        return await api_fn(ctx).get_pipeline_status(session_id)
