from fastapi import APIRouter, File, UploadFile, Depends, HTTPException, status, Form
from sqlmodel import Session

from app.db.session import get_session
from app.api.deps import require_roles
from app.models.user import User, Role
from app.services.product_image_service import ProductImageService
from app.core.logging import setup_logger

logger = setup_logger(__name__)
router = APIRouter(prefix="/api/product-images", tags=["Product Images"])


@router.post(
    "/generate",
    status_code=status.HTTP_201_CREATED,
    summary="Generate final image for a project using a template unique_name"
)
async def generate_final_image_for_project(
    project_master_id: int = Form(..., description="Project master id"),
    template_unique_name: str = Form(..., description="Template unique name"),
    db: Session = Depends(get_session),
    current_user: User = Depends(require_roles(Role.SUPERADMIN, Role.ADMIN)),
):
    """
    Frontend will POST project_master_id and template_unique_name.
    This endpoint will generate the final image, product-resized image (if applicable),
    create thumbnails and persist a ProductImage row.
    """
    try:
        product_image = await ProductImageService.generate_for_project(
            session=db,
            project_id=project_master_id,
            template_unique_name=template_unique_name,
            current_user_id=current_user.id,
        )
        # return a stable JSON representation
        return {
            "id": product_image.id,
            "project_master_id": product_image.project_master_id,
            "product_template_id": product_image.product_template_id,
            "final_image_path": product_image.final_image_path,
            "final_image_thumbnail_path": product_image.final_image_thumbnail_path,
            "final_image_product_path": product_image.final_image_product_path
        }
    except HTTPException:
        raise
    except Exception:
        logger.exception("Unexpected error while generating final image")
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to generate image")

@router.patch(
    "/regenerate-image/{product_image_id}",
    status_code=status.HTTP_200_OK
)
async def regenerate_single_image_endpoint(
    product_image_id: int,
    new_overlay_image: UploadFile = File(...),
    color: str | None = Form(None, description="Hex color to apply to template's color layer"),
    db: Session = Depends(get_session),
    current_user: User = Depends(require_roles(Role.ADMIN, Role.SUPERADMIN)),
):
    return await ProductImageService.regenerate_single_image(
        db=db,
        product_image_id=product_image_id,
        new_overlay_file=new_overlay_image,
        color=color,
        current_user=current_user
    )
