"""Optovia Agents - Main entry point for all agents.

This module sets up the Playground with:
- Logistics Agent: Chat agent with MCP tools for product/offer/route queries
- EGRUL Agent: AI agent for getting company data from Russian EGRUL registry

Run with: poetry run python app.py
"""

import os
from pathlib import Path

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from agno.agent import Agent
from agno.models.google import Gemini
from agno.playground import Playground
from agno.tools.mcp import MCPTools
from mcp import StdioServerParameters

from agents.egrul import run_egrul_agent


def create_mcp_tools() -> MCPTools:
    """Create MCPTools instance for Optovia MCP server."""
    mcp_path = Path(__file__).parent / "mcp" / "src" / "index.js"

    server_params = StdioServerParameters(
        command="node",
        args=[str(mcp_path)],
        env={
            **os.environ,
            "GEO_GRAPHQL_URL": os.getenv("GEO_GRAPHQL_URL", ""),
            "EXCHANGE_GRAPHQL_URL": os.getenv("EXCHANGE_GRAPHQL_URL", ""),
            "ORDERS_GRAPHQL_URL": os.getenv("ORDERS_GRAPHQL_URL", ""),
            "GEO_M2M_TOKEN": os.getenv("GEO_M2M_TOKEN", ""),
        },
    )

    return MCPTools(server_params=server_params)


def create_logistics_agent(mcp_tools: MCPTools) -> Agent:
    """Create the logistics chat agent."""
    return Agent(
        agent_id="logistics-agent",
        name="Logistics Agent",
        model=Gemini(id="gemini-2.0-flash"),
        tools=[mcp_tools],
        instructions="""You are a logistics assistant for the Optovia commodity trading platform.

You help users with:
- Finding products and offers on the exchange (cocoa, coffee, grains, etc.)
- Searching logistics nodes (ports, terminals, warehouses) by name or location
- Building optimal routes from offer sources to destination hubs
- Tracking order status and shipment timelines

Available tools:
- search_products: Find products by name
- search_offers: Find active offers, can filter by product/category/location
- search_nodes: Find logistics nodes by name or transport type
- nearest_nodes: Find nodes near given coordinates
- match_offers_with_route: Get route options from product offers to destination
- order_timeline: Get order details with stages and trips (requires auth)

Always be concise and provide actionable information. When showing routes,
include distances and estimated times. Format prices with currency.""",
        markdown=True,
    )


# Create MCP tools for logistics agent
mcp_tools = create_mcp_tools()

# Create agents
logistics_agent = create_logistics_agent(mcp_tools)

# Create Playground with only logistics agent (EGRUL via direct API)
playground = Playground(agents=[logistics_agent])

# FastAPI app
app = playground.get_app()


# Direct EGRUL API endpoint (creates fresh MCP connection per request)
class EgrulRequest(BaseModel):
    inn: str


class EgrulResponse(BaseModel):
    content: str
    success: bool
    error: str | None = None


@app.post("/api/egrul", response_model=EgrulResponse)
async def fetch_egrul(request: EgrulRequest):
    """Fetch EGRUL data for a company by INN.

    Creates fresh MCP/Playwright connection for each request.
    """
    try:
        content = await run_egrul_agent(request.inn)
        return EgrulResponse(content=content, success=True)
    except Exception as e:
        return EgrulResponse(content="", success=False, error=str(e))


if __name__ == "__main__":
    """
    Run the Playground server.

    API docs available at: http://localhost:8000/docs
    """
    playground.serve(app="app:app", host="0.0.0.0", port=8000)
