import base64
import logging
from fastapi import APIRouter, UploadFile, File, HTTPException
from pathlib import Path
import uuid

from app.constants import error_codes
from app.core.constants import MAX_FILE_SIZE_BYTES, ALLOWED_UPLOAD_CONTENT_TYPES
from app.services.gemini import extract_from_image

logger = logging.getLogger(__name__)

router = APIRouter()

UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)


@router.post("")
async def upload_file(file: UploadFile = File(...)):
    if file.content_type not in ALLOWED_UPLOAD_CONTENT_TYPES:
        raise HTTPException(
            status_code=400,
            detail={"error": error_codes.UNSUPPORTED_FILE_TYPE, "message": f"{file.content_type} is not a supported file type"},
        )

    contents = await file.read()
    if len(contents) > MAX_FILE_SIZE_BYTES:
        raise HTTPException(
            status_code=400,
            detail={"error": error_codes.FILE_TOO_LARGE, "message": "File exceeds the 10MB size limit"},
        )

    ext = Path(file.filename or "").suffix
    stored_name = f"{uuid.uuid4().hex}{ext}"
    with open(UPLOAD_DIR / stored_name, "wb") as f:
        f.write(contents)

    extracted_info = None
    if file.content_type.startswith("image/"):
        try:
            extracted_info = await extract_from_image(base64.b64encode(contents).decode(), file.content_type)
        except Exception as exc:
            # EXTRACTION_FAILED is silent — log it server-side only, never surface it to the user.
            # Upload itself already succeeded, so this never fails the upload.
            logger.error("[EXTRACTION_FAILED] status=500 file=%r contentType=%r detail=%s", file.filename, file.content_type, exc, exc_info=exc)

    return {
        "url": f"/media/{stored_name}",
        "filename": file.filename,
        "contentType": file.content_type,
        "sizeBytes": len(contents),
        "extractedInfo": extracted_info,
    }
