from fastapi import FastAPI, Depends, HTTPException
from contextlib import asynccontextmanager
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy import MetaData, Table, inspect
from minio import Minio
from minio.error import S3Error
import os

from models import Base, LabeledData
from schemas import LabeledDataCreate
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import sessionmaker
import pandas as pd
from io import StringIO, BytesIO
from database import engine, get_db, SessionLocal
from config import MINIO_SERVER, MINIO_MODEL_TRAINED, MINIO_DATA_LABELED
from utils import check_bucket

minio_client = Minio(
    endpoint=MINIO_SERVER,
    access_key=os.getenv("MINIO_ROOT_USER"),
    secret_key=os.getenv("MINIO_ROOT_PASSWORD"),
    secure=False
)
bucket_names = [MINIO_DATA_LABELED, MINIO_MODEL_TRAINED]


@asynccontextmanager
async def lifespan(app: FastAPI):
    check_bucket(minio_client=minio_client, bucket_names=bucket_names)
    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

