from fastapi import FastAPI, Request, Response
from fastapi.staticfiles import StaticFiles
from requests import request as make_request

from api.routers import runs

# from api.optimization import Backend

DEBUG = True

app = FastAPI(debug=DEBUG, title="Prompt Optimization Backend")
app.include_router(runs.router, prefix="/api/runs")
if DEBUG:

    @app.get("/{_:path}")
    async def frontent_dev(request: Request):
        response = make_request(
            method=request.method,
            url=f"{request.url.replace(port=3000)}",
            headers=request.headers,
            stream=True,
        )
        return Response(
            content=response.raw.read(),
            status_code=response.status_code,
            headers=response.headers,
            media_type=response.headers["content-type"],
        )

else:
    app.mount("/", StaticFiles(directory="frontend/build/", html=True), name="frontend")


def test():
    pass


# @app.get("/test")
# async def test_long_operation(request: Request):
#     loop = asyncio.get_event_loop()
#     result = await loop.run_in_executor(pool, test)
#     return "ok"


# start optimization
@app.get("/run/{num_iterations}")
async def run(num_iterations: int) -> str:
    # api.run_optimization(num_iterations)
    return "ok"


# TODO turn actions into router and allow to set actions dynamically
# perform optimizer-specific action
@app.get("/action/evolve/")
async def evolve(prompt1: str, prompt2: str) -> str:
    return f"This is the evolved prompt taking prompts {prompt1} and {prompt2} into account."


# get current genealogy of prompts
@app.get("/family_tree/get")
async def get_family() -> dict:
    return dict()