import os
from typing import List

import httpx

PLANTNET_KEY = os.environ.get("PLANTNET_API_KEY", "")
PLANTNET_URL = "https://my-api.plantnet.org/v2/identify/all"


async def identify(image_bytes: bytes, filename: str = "photo.jpg") -> List[dict]:
    """Appelle PlantNet et retourne les 3 meilleures identifications."""
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            resp = await client.post(
                PLANTNET_URL,
                params={"api-key": PLANTNET_KEY, "nb-results": 3, "lang": "fr"},
                files={"images": (filename, image_bytes, "image/jpeg")},
                data={"organs": ["auto"]},
            )
            resp.raise_for_status()
            data = resp.json()
    except Exception:
        return []

    results = []
    for r in data.get("results", [])[:3]:
        species = r.get("species", {})
        common_names = species.get("commonNames", [])
        results.append({
            "species": species.get("scientificNameWithoutAuthor", ""),
            "common_name": common_names[0] if common_names else "",
            "confidence": round(r.get("score", 0.0), 3),
            "image_url": (r.get("images", [{}]) or [{}])[0].get("url", {}).get("m", ""),
        })
    return results
