from fastapi import FastAPI, Depends, HTTPException
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncSession

from models import Base, LabeledData
from schemas import LabeledDataCreate
from database import engine, get_db, SessionLocal
from constants import MINIO_SERVER, MINIO_MODEL_TRAINED, MINIO_DATA_LABELED
from minio_client import check_bucket

@asynccontextmanager
async def lifespan(app: FastAPI):
    check_bucket()
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
    yield

app = FastAPI(lifespan=lifespan)

@app.post("/add-data", response_model=LabeledDataCreate)
async def create_labeled_data(data: LabeledDataCreate, db: AsyncSession = Depends(get_db)):
    new_data = LabeledData(paragraph=data.paragraph, label=data.label)
    try:
        db.add(new_data)
        await db.commit()
        await db.refresh(new_data)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    return new_data

