from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from services import sdbackend as sd_service
from services.memory import get_last_assistant_message_id, update_message_image

router = APIRouter(prefix="/images", tags=["images"])


class GenerateRequest(BaseModel):
    session_id: str
    prompt: str


@router.get("/health")
async def sd_health():
    ok = await sd_service.check_sd()
    return {"sd_available": ok, "url": sd_service.SD_BASE_URL}


@router.post("/generate")
async def generate_image(req: GenerateRequest):
    if not req.prompt.strip():
        raise HTTPException(status_code=400, detail="Пустой промпт")

    rel, err = await sd_service.generate_from_full_prompt(req.prompt)
    if not rel:
        raise HTTPException(status_code=502, detail=err or "SD backend недоступен")

    msg_id = await get_last_assistant_message_id(req.session_id)
    if msg_id:
        await update_message_image(msg_id, rel)

    return {"image_path": f"/static/{rel}", "status": "ok"}
