from __future__ import annotations

import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from mcp.server.fastmcp import FastMCP

from mcp_server_propel.propel_client import PropelClient
from mcp_server_propel.tools.review_tools import (
    check_review_status,
    get_review,
    submit_review,
)


@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[PropelClient]:
    token = os.environ.get("PROPEL_API_TOKEN", "").strip()
    if not token:
        raise ValueError(
            "PROPEL_API_TOKEN environment variable is required.\n"
            "\n"
            "To get a token:\n"
            "  1. Go to https://propelcode.ai/settings/api\n"
            "  2. Create a token with 'reviews:write' scope\n"
            "  3. Set it in your Claude Desktop config or environment"
        )

    base_url = os.environ.get("PROPEL_API_URL", "https://api.propelcode.ai")
    client = PropelClient(api_token=token, base_url=base_url)
    try:
        yield client
    finally:
        await client.aclose()


mcp = FastMCP("propel", lifespan=app_lifespan)

mcp.tool()(submit_review)
mcp.tool()(get_review)
mcp.tool()(check_review_status)


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


if __name__ == "__main__":
    main()
