"""
Quality Inspection API Routes
"""
from fastapi import APIRouter, HTTPException, UploadFile, File, Query
from typing import Optional
from pydantic import BaseModel

from app.services.quality_service import quality_service

router = APIRouter()


class DimensionSpec(BaseModel):
    width: Optional[float] = None
    height: Optional[float] = None


@router.post("/inspect", summary="Inspect surface for defects")
async def inspect_surface(
    file: UploadFile = File(...),
    sensitivity: str = Query("medium", description="Detection sensitivity: low, medium, high"),
    reference: Optional[UploadFile] = File(None)
):
    """
    Inspect an image for surface defects
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    if sensitivity not in ["low", "medium", "high"]:
        raise HTTPException(status_code=400, detail="Sensitivity must be low, medium, or high")

    contents = await file.read()
    reference_contents = await reference.read() if reference else None

    result = await quality_service.inspect_surface(contents, sensitivity, reference_contents)

    return {
        "filename": file.filename,
        **result
    }


@router.post("/inspect/dimensions", summary="Check object dimensions")
async def inspect_dimensions(
    file: UploadFile = File(...),
    expected_width: Optional[float] = Query(None, description="Expected width"),
    expected_height: Optional[float] = Query(None, description="Expected height"),
    pixels_per_unit: float = Query(1.0, description="Calibration: pixels per unit")
):
    """
    Check if object dimensions match expected values
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    expected = {}
    if expected_width:
        expected["width"] = expected_width
    if expected_height:
        expected["height"] = expected_height

    if not expected:
        raise HTTPException(status_code=400, detail="At least one expected dimension required")

    contents = await file.read()
    result = await quality_service.inspect_dimensions(contents, expected, pixels_per_unit)

    return {
        "filename": file.filename,
        **result
    }


@router.post("/compare", summary="Compare with reference image")
async def compare_images(
    test_image: UploadFile = File(...),
    reference_image: UploadFile = File(...),
    sensitivity: str = Query("medium")
):
    """
    Compare test image with reference for quality differences
    """
    if not test_image.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Test image must be an image file")
    if not reference_image.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Reference image must be an image file")

    test_contents = await test_image.read()
    ref_contents = await reference_image.read()

    result = await quality_service.inspect_surface(test_contents, sensitivity, ref_contents)

    return {
        "test_filename": test_image.filename,
        "reference_filename": reference_image.filename,
        **result
    }


@router.get("/defect-types", summary="Get supported defect types")
async def get_defect_types():
    """
    Get list of defect types the system can detect
    """
    return {
        "defect_types": quality_service.defect_types,
        "severity_levels": ["low", "medium", "high"]
    }
