# See src/mcp_guide/tools/README.md for tool documentation standards

"""Documentation update tool."""

from pathlib import Path
from typing import Optional

from mcp_guide.core.tool_arguments import ToolArguments
from mcp_guide.core.tool_decorator import toolfunc
from mcp_guide.installer.core import ORIGINAL_ARCHIVE, perform_locked_update, read_version
from mcp_guide.result import Result
from mcp_guide.result_constants import ERROR_NO_PROJECT, INSTRUCTION_NO_PROJECT
from mcp_guide.session import get_or_create_session
from mcp_guide.tools.tool_result import tool_result

try:
    from mcp.server.fastmcp import Context
except ImportError:
    Context = None  # type: ignore

__all__ = ["internal_update_documents", "update_documents"]


class UpdateDocumentsArgs(ToolArguments):
    """Arguments for update_documents tool."""

    pass


async def internal_update_documents(
    args: UpdateDocumentsArgs,
    ctx: Optional[Context] = None,  # type: ignore
) -> Result[dict]:  # type: ignore[type-arg]
    """Update documentation files in the current project.

    Checks for version changes and updates files using smart merge strategy.
    Uses file locking to prevent concurrent updates.

    Args:
        args: Tool arguments (currently no parameters)
        ctx: MCP Context (auto-injected by FastMCP)

    Returns:
        Result containing update statistics
    """
    try:
        session = await get_or_create_session(ctx)
    except ValueError as e:
        return Result.failure(
            error=str(e),
            error_type=ERROR_NO_PROJECT,
            instruction=INSTRUCTION_NO_PROJECT,
        )

    docroot = Path(await session.get_docroot())
    archive_path = docroot / ORIGINAL_ARCHIVE

    # Check version
    from mcp_guide import __version__

    current_version = await read_version(docroot)
    if current_version == __version__:
        return Result.ok(value={"message": f"Already at version {__version__}", "updated": False})

    # Perform locked update
    stats = await perform_locked_update(docroot, archive_path)

    return Result.ok(
        value={
            "message": "Documentation updated successfully",
            "updated": True,
            "stats": stats,
        }
    )


@toolfunc(UpdateDocumentsArgs)
async def update_documents(
    args: UpdateDocumentsArgs,
    ctx: Optional[Context] = None,  # type: ignore
) -> str:
    """Update documentation files in the current project.

    Checks for version changes and updates files using smart merge strategy.
    Uses file locking to prevent concurrent updates.

    ## JSON Schema

    ```json
    {
      "type": "object",
      "properties": {}
    }
    ```

    ## Usage Instructions

    ```python
    # Update documentation files
    await update_documents(UpdateDocumentsArgs())
    ```

    ## Concrete Examples

    ```python
    # Example: Update documentation
    result = await update_documents(UpdateDocumentsArgs())
    # Returns: {"message": "Documentation updated successfully", "updated": true, "stats": {...}}
    ```
    """
    result = await internal_update_documents(args, ctx)
    return await tool_result("update_documents", result)
