"""
Tool 1 — Analyse du bien immobilier.
Extrait les informations et calcule le prix au m².
"""

import json
import logging

logger = logging.getLogger("tools.analyze_property")


def _parse(parametre: str) -> dict:
    try:
        return json.loads(parametre)
    except (json.JSONDecodeError, TypeError):
        logger.warning(f"Paramètre non parseable : {parametre!r}")
        return {}


def analyze_property(parametre: str) -> dict:
    """
    Analyse un bien immobilier et calcule son prix au m².

    Paramètre JSON :
        {"prix": number, "surface": number, "ville": string, "type_bien": string}

    Formule :
        prix_m2 = prix / surface
    """
    data = _parse(parametre)

    prix      = data.get("prix")
    surface   = data.get("surface")
    ville     = data.get("ville", "inconnue")
    type_bien = data.get("type_bien", "inconnu")

    if not prix or not surface:
        return {"erreur": "Les champs 'prix' et 'surface' sont requis."}
    if surface <= 0:
        return {"erreur": "La surface doit être supérieure à 0."}

    prix_m2 = round(prix / surface, 2)

    result = {
        "ville":      ville,
        "type_bien":  type_bien,
        "surface_m2": surface,
        "prix_total": prix,
        "prix_m2":    prix_m2,
    }
    logger.info(f"analyze_property → prix_m2={prix_m2} €/m²")
    return result
