from typing import Annotated, Union

from fastapi import FastAPI, Request, status, Form
from fastapi.responses import JSONResponse

from src.dotchain.runtime.interpreter import program_parser
from src.dotchain.runtime.tokenizer import Tokenizer
from src.dotchain.runtime.runtime import Runtime
from src.blackbox.blackbox_factory import BlackboxFactory
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from injector import Injector

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

injector = Injector()
blackbox_factory = injector.get(BlackboxFactory)

@app.post("/")
async def blackbox(blackbox_name: Union[str, None] = None, request: Request = None):
    if not blackbox_name:
        return await JSONResponse(content={"error": "blackbox_name is required"}, status_code=status.HTTP_400_BAD_REQUEST)
    try:
        box = blackbox_factory.call_blackbox(blackbox_name)
    except ValueError:
        return await JSONResponse(content={"error": "value error"}, status_code=status.HTTP_400_BAD_REQUEST)
    return await box.fast_api_handler(request)
