"""GPAI MCP Server - expose solve as a tool for AI agents."""

import json

from mcp.server.fastmcp import FastMCP

from gpai_cli.client import GPAIClient
from gpai_cli.solve_core import run_solve

mcp = FastMCP(
    "gpai",
    instructions="GPAI AI-powered problem solver. Solve math/science problems from images.",
)


@mcp.tool()
def solve(image_path: str) -> str:
    """Solve a math/science problem from an image file.

    Uploads the image, runs AI-powered solving, waits for completion
    (including visual generation), and returns the solution.

    Args:
        image_path: Absolute path to the problem image file (png, jpg, etc).

    Returns:
        JSON with: answer, solution (markdown with LaTeX), visuals (image URLs), task_id.
    """
    try:
        client = GPAIClient()
        result = run_solve(client, image_path)
        return json.dumps(
            {
                "answer": result["answer"],
                "solution": result["solution"],
                "visuals": result["visuals"],
                "image_url": result["image_url"],
                "task_id": result["task_id"],
            },
            ensure_ascii=False,
        )
    except Exception as e:
        return json.dumps({"error": str(e)})


def main() -> None:
    mcp.run()


if __name__ == "__main__":
    main()
