from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import SessionLocal
from pydantic import BaseModel

from models.api_modal import LLMSettings

router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class LLMSettingsIn(BaseModel):
    api_key: str
    model: str

@router.post("/llm-settings")
def set_llm_settings(settings: LLMSettingsIn, db: Session = Depends(get_db)):
    existing = db.query(LLMSettings).first()
    if existing:
        existing.api_key = settings.api_key
        existing.model = settings.model
    else:
        db.add(LLMSettings(api_key=settings.api_key, model=settings.model))
    db.commit()
    return {"message": "LLM settings updated"}