"""
Router détection de fraude — analyse d'images de diplômes.
"""
import logging
import os
import tempfile

from fastapi import APIRouter, File, HTTPException, UploadFile

from app.schemas.fraud import FraudDetectionResponse
from app.services.fraud_service import fraud_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/ai", tags=["fraud-detection"])

ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".tiff", ".bmp"}
MAX_FILE_SIZE = 10 * 1024 * 1024  # 10 MB


@router.post("/detect-fraud", response_model=FraudDetectionResponse, summary="Analyser un diplôme pour détecter une fraude")
async def detect_fraud(file: UploadFile = File(...)) -> FraudDetectionResponse:
    """
    Analyse une image de diplôme pour détecter des falsifications.

    Techniques utilisées :
    - **ELA** (Error Level Analysis) : révèle les zones retouchées
    - **Métadonnées EXIF** : détecte les logiciels d'édition (Photoshop, GIMP…)
    - **Zones uniformes** : détecte les collages
    - **Histogramme** : détecte les anomalies de distribution des couleurs

    Retourne un score de confiance (0-1) et un niveau de risque (low/medium/high).
    """
    # Validation de l'extension
    if file.filename:
        ext = os.path.splitext(file.filename)[1].lower()
        if ext not in ALLOWED_EXTENSIONS:
            raise HTTPException(
                status_code=422,
                detail=f"Format non supporté. Formats acceptés : {', '.join(ALLOWED_EXTENSIONS)}",
            )

    # Lecture du contenu
    content = await file.read()

    if len(content) > MAX_FILE_SIZE:
        raise HTTPException(status_code=413, detail="Fichier trop volumineux (max 10 MB)")

    if len(content) == 0:
        raise HTTPException(status_code=422, detail="Fichier vide")

    # Analyse dans un fichier temporaire
    try:
        suffix = os.path.splitext(file.filename or ".jpg")[1] or ".jpg"
        with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
            tmp.write(content)
            tmp_path = tmp.name

        result = fraud_service.analyze_image(tmp_path)
        return FraudDetectionResponse(**result)

    except Exception as exc:
        logger.exception("Erreur detect_fraud : %s", exc)
        raise HTTPException(status_code=500, detail=f"Erreur d'analyse : {exc}")

    finally:
        if "tmp_path" in locals() and os.path.exists(tmp_path):
            os.unlink(tmp_path)
