"""
Tool 6 — Génération du rapport d'investissement en Markdown.
À appeler en dernier, une fois toutes les données rassemblées.
"""

import json
import logging

logger = logging.getLogger("tools.generate_report")


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 generate_report(parametre: str) -> dict:
    """
    Génère un rapport d'investissement formaté en Markdown.

    Paramètre JSON — compilation de l'analyse complète :
        {
          "bien":                   {...},
          "analyse_marche":         {...},
          "indicateurs_financiers": {...},
          "score_investissement":   {...},
          "conclusion":             "string",
          "recommandation":         "string"
        }

    Retour :
        {"format": "markdown", "rapport": "# Investment Report ..."}
    """
    data = _parse(parametre)
    if not data:
        return {"erreur": "Données insuffisantes pour générer le rapport."}

    bien    = data.get("bien", {})
    marche  = data.get("analyse_marche", {})
    fin     = data.get("indicateurs_financiers", {})
    score   = data.get("score_investissement", {})
    details = score.get("details", {})
    conclusion     = data.get("conclusion", "N/A")
    recommandation = data.get("recommandation", "N/A")

    def v(d, key, unit=""):
        val = d.get(key)
        return "N/A" if val is None else f"{val}{unit}"

    rapport = f"""# Investment Report
---

## Property Summary
| Champ | Valeur |
|---|---|
| Ville | {v(bien, 'ville')} |
| Type | {v(bien, 'type_bien')} |
| Surface | {v(bien, 'surface_m2')} m² |
| Prix total | {v(bien, 'prix_total')} € |
| Prix au m² | {v(bien, 'prix_m2')} €/m² |

## Market Analysis
| Indicateur | Valeur |
|---|---|
| Prix m² moyen marché | {v(marche, 'prix_m2_moyen')} €/m² |
| Position marché | {v(marche, 'position_marche')} |
| Loyer m² moyen | {v(marche, 'loyer_m2_moyen')} €/m² |
| Demande locative | {v(marche, 'demande_locative')} |
| Tendance marché | {v(marche, 'tendance_marche')} |

## Financial Indicators
| Indicateur | Valeur |
|---|---|
| Loyer mensuel estimé | {v(fin, 'loyer_mensuel_estime')} € |
| Loyer annuel | {v(fin, 'loyer_annuel')} € |
| Charges annuelles | {v(fin, 'charges_annuelles')} € |
| Rentabilité brute | {v(fin, 'rentabilite_brute')} % |
| Rentabilité nette | {v(fin, 'rentabilite_nette')} % |

## Investment Score : {v(score, 'score')} / 10 — {v(score, 'niveau').upper()}

| Critère | Score | Poids |
|---|---|---|
| Rentabilité | {v(details, 'rentabilite')} | 40 % |
| Prix marché | {v(details, 'prix_marche')} | 30 % |
| Demande locative | {v(details, 'demande_locative')} | 20 % |
| Risque | {v(details, 'risque')} | 10 % |

## Conclusion
{conclusion}

## Recommandation
{recommandation}
"""

    logger.info("generate_report → rapport Markdown généré")
    return {"format": "markdown", "rapport": rapport}
