"""Repository management tools — connect, scan, status, and health checks."""

from __future__ import annotations

from mcp.server import FastMCP

from g8_mcp_server.client import G8Client, format_result


def register(server: FastMCP, client: G8Client) -> None:
    """Register all repo tools on the MCP server."""

    @server.tool()
    async def g8_connect_repo(repo_url: str, repo_name: str, provider: str = "github", default_branch: str = "main") -> str:
        """Connect a GitHub/GitLab repository to graph8 for GTM automation.

        After connecting, run g8_scan_repo to analyze the tech stack.

        Args:
            repo_url: Full repository URL (e.g. https://github.com/org/repo)
            repo_name: Short name for the repo (e.g. my-saas-app)
            provider: Repository provider — github, gitlab, or local
            default_branch: Default branch name (usually main)
        """
        result = await client.post("/repos", {"repo_url": repo_url, "repo_name": repo_name, "provider": provider, "default_branch": default_branch})
        return format_result(result)

    @server.tool()
    async def g8_scan_repo(repo_id: str) -> str:
        """Scan a connected repository for tech stack, API routes, and GTM readiness.

        This triggers a scan on the backend. Use g8_get_scan_results to retrieve
        results if the scan is still processing.

        Args:
            repo_id: Repository ID from g8_connect_repo or g8_status
        """
        result = await client.post(f"/repos/{repo_id}/scan", {})
        return format_result(result)

    @server.tool()
    async def g8_get_scan_results(repo_id: str) -> str:
        """Get the latest scan results for a repository.

        Returns detected tech stack, API routes, README summary, and GTM readiness flags.

        Args:
            repo_id: Repository ID
        """
        result = await client.get(f"/repos/{repo_id}/scan")
        return format_result(result)

    @server.tool()
    async def g8_status(repo_id: str) -> str:
        """Get the current status of a connected repository.

        Returns repo metadata, scan status, and install status.

        Args:
            repo_id: Repository ID
        """
        result = await client.get(f"/repos/{repo_id}")
        return format_result(result)

    @server.tool()
    async def g8_doctor(repo_id: str) -> str:
        """Run health checks on a repository's GTM installation.

        Verifies that tracking, forms, identity resolution, and attribution
        are correctly installed and functioning.

        Args:
            repo_id: Repository ID
        """
        result = await client.post(f"/repos/{repo_id}/verify", {})
        return format_result(result)
