from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, Optional


@dataclass
class ESGScore:
    supplier_id: str
    score: float  # 0..100
    rationale: str


def simple_esg_score(
    supplier_id: str,
    factors: Dict[str, float],
    weights: Optional[Dict[str, float]] = None,
) -> ESGScore:
    """
    factors example:
      {"co2_intensity": 0.7, "labor_risk": 0.2, "compliance": 0.9}  # normalized 0..1 (higher is better)
    """
    if not factors:
        return ESGScore(supplier_id=supplier_id, score=0.0, rationale="No factors provided.")

    if weights is None:
        weights = {k: 1.0 for k in factors.keys()}

    total_w = 0.0
    total = 0.0
    for k, v in factors.items():
        w = float(weights.get(k, 1.0))
        total_w += w
        total += w * float(v)

    normalized = (total / total_w) if total_w > 0 else 0.0
    score = max(0.0, min(100.0, normalized * 100.0))

    rationale = "Weighted ESG score from normalized factors: " + ", ".join(
        f"{k}={v:.2f}" for k, v in factors.items()
    )
    return ESGScore(supplier_id=supplier_id, score=score, rationale=rationale)

