from fastapi import APIRouter, File, UploadFile
from app.services import plantnet, yolo_service, redis_cache

router = APIRouter(tags=["identification"])


@router.post("/identify")
async def identify_plant(file: UploadFile = File(...)):
    image_bytes = await file.read()

    # 1. Cache Redis
    cached = redis_cache.get(image_bytes)
    if cached is not None:
        return {"source": "cache", "results": cached}

    # 2. PlantNet (cloud)
    results = await plantnet.identify(image_bytes, file.filename or "photo.jpg")

    # 3. Fallback YOLO si PlantNet indisponible
    if not results:
        results = await yolo_service.identify(image_bytes)
        source = "yolo"
    else:
        source = "plantnet"

    # 4. Mettre en cache uniquement si des résultats ont été trouvés
    if results:
        redis_cache.set(image_bytes, results)

    return {"source": source, "results": results}
