from fastapi import APIRouter, HTTPException
import httpx

from app.config import settings
from app.schemas.image import DepthProcessingResponse, DepthProcessingRequest, ImageUpdate
from app.services.image_service import create_image, patch_image

router = APIRouter()


@router.post("/depth-process", response_model=DepthProcessingResponse)
async def depth_process(request: DepthProcessingRequest):
    try:
        image = await create_image(request)
        async with httpx.AsyncClient() as client:
            response = await client.post(settings.AI_SERVER_URL, json={
                "input_url": str(request.input_url),
                "encoder": request.encoder
            }, timeout=30.0)

            response.raise_for_status()
            response_data = response.json()

            # Update image với processed_url
            update_data = ImageUpdate(
                processed_url=response_data.get("output_url")
            )

            # Update image với processed_url
            await patch_image(
                str(image["_id"]),
                update_data
            )
            return response.json()
    except httpx.TimeoutException:
        raise HTTPException(
            status_code=504,
            detail="AI server processing timeout"
        )
    except httpx.HTTPError as e:
        raise HTTPException(
            status_code=e.response.status_code if hasattr(e, 'response') else 500,
            detail=f"AI server error: {str(e)}"
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Internal server error: {str(e)}"
        )
