{# templates/restpipe.py.jinja2 #}
from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI, HTTPException  # https://fastapi.tiangolo.com/
from fastapi.security import APIKeyHeader
from superagentx.agentxpipe import AgentXPipe
from superagentx.result import GoalResult

from {{ package_name }}.config import AUTH_TOKEN
from {{ package_name }}.pipe import get_{{ pipe_name }}_pipe

pipes = {}


@asynccontextmanager
async def lifespan(app: FastAPI):
    pipes['{{ pipe_name }}_pipe'] = await get_{{ pipe_name }}_pipe()
    yield
    pipes.clear()


{{ package_name }}_app = FastAPI(
    title='{{ app_name }} Search',
    lifespan=lifespan,
    docs_url='/app/rest/docs',
    openapi_url='/app/rest/openapi.json'
)


async def verify_api_token(
    api_token: str = Depends(APIKeyHeader(name='api-token', auto_error=False))
):
    if api_token != AUTH_TOKEN:
        raise HTTPException(status_code=401, detail='Invalid API Token!')


@{{ package_name }}_app.get('/app/rest/health')
async def index():
    return {"name": '{{ app_name }} Search SuperagentX App'}


@{{ package_name }}_app.get('/app/rest/search', dependencies=[Depends(verify_api_token)])
async def search(query: str) -> list[GoalResult]:
    {{ pipe_name }}_pipe: AgentXPipe = pipes.get('{{ pipe_name }}_pipe')
    return await {{ pipe_name }}_pipe.flow(query_instruction=query)


"""
# To Run this, `pip install 'fastapi[standard]'`

# Development Mode
fastapi dev {{ app_name }}/{{ package_name }}/rest_pipe.py

# Server Mode
fastapi run {{ app_name }}/{{ package_name }}/rest_pipe.py
"""{{'\n'}}