#!/usr/bin/env python3
"""Matriz de decisión ponderada con requisitos eliminatorios y análisis de sensibilidad.

Uso:
    python weighted_matrix.py entrada.json [--delta 0.2] [--markdown] [--json]

Formato de entrada (JSON):
    {
      "title": "opcional",
      "criteria": [{"id": "coste", "weight": 0.3, "rationale": "..."}, ...],
      "alternatives": [
        {"id": "A", "must_pass": true, "scores": {"coste": 4, ...}, "evidence": {"coste": "BOM v0.2"}},
        {"id": "C", "must_pass": false, "fail_reason": "No cumple REQ-NF-001"}
      ]
    }

Las puntuaciones están orientadas (5 = mejor) en escala 1-5. Solo usa la biblioteca estándar.
"""
from __future__ import annotations

import argparse
import json
import sys
from dataclasses import dataclass, field

SCORE_MIN, SCORE_MAX = 1.0, 5.0
WEIGHT_TOLERANCE = 1e-6


class MatrixError(ValueError):
    """Error de validación de la matriz de decisión."""


@dataclass
class Result:
    totals: dict[str, float]
    ranking: list[str]
    eliminated: dict[str, str]
    weights: dict[str, float]
    normalized: bool
    sensitivity: list[dict] = field(default_factory=list)

    @property
    def winner(self) -> str | None:
        return self.ranking[0] if self.ranking else None

    @property
    def fragile(self) -> bool:
        return any(row["winner"] != self.winner for row in self.sensitivity)


def _weights(criteria: list[dict]) -> tuple[dict[str, float], bool]:
    if not criteria:
        raise MatrixError("La matriz necesita al menos un criterio.")
    weights: dict[str, float] = {}
    for c in criteria:
        cid = c.get("id")
        if not cid:
            raise MatrixError("Todos los criterios necesitan 'id'.")
        if cid in weights:
            raise MatrixError(f"Criterio duplicado: {cid}")
        w = float(c.get("weight", 0))
        if w < 0:
            raise MatrixError(f"Peso negativo en {cid}")
        weights[cid] = w
    total = sum(weights.values())
    if total <= 0:
        raise MatrixError("La suma de pesos debe ser positiva.")
    normalized = abs(total - 1.0) > WEIGHT_TOLERANCE
    if normalized:
        weights = {k: v / total for k, v in weights.items()}
    return weights, normalized


def _score_totals(alternatives: list[dict], weights: dict[str, float]) -> tuple[dict[str, float], dict[str, str]]:
    totals: dict[str, float] = {}
    eliminated: dict[str, str] = {}
    for alt in alternatives:
        aid = alt.get("id")
        if not aid:
            raise MatrixError("Todas las alternativas necesitan 'id'.")
        if aid in totals or aid in eliminated:
            raise MatrixError(f"Alternativa duplicada: {aid}")
        if not alt.get("must_pass", True):
            eliminated[aid] = alt.get("fail_reason", "No cumple un requisito obligatorio")
            continue
        scores = alt.get("scores", {})
        missing = [c for c in weights if c not in scores]
        if missing:
            raise MatrixError(f"A la alternativa {aid} le faltan puntuaciones: {', '.join(missing)}")
        total = 0.0
        for cid, w in weights.items():
            s = float(scores[cid])
            if not SCORE_MIN <= s <= SCORE_MAX:
                raise MatrixError(f"Puntuación fuera de rango [1, 5] en {aid}/{cid}: {s}")
            total += w * s
        totals[aid] = total
    return totals, eliminated


def _ranking(totals: dict[str, float]) -> list[str]:
    return sorted(totals, key=lambda a: (-totals[a], a))


def perturb(weights: dict[str, float], criterion: str, factor: float) -> dict[str, float]:
    """Multiplica el peso de `criterion` por `factor` y reescala el resto para que la suma sea 1."""
    if criterion not in weights:
        raise MatrixError(f"Criterio desconocido: {criterion}")
    new_wk = min(max(weights[criterion] * factor, 0.0), 1.0)
    rest = 1.0 - weights[criterion]
    out = {}
    for cid, w in weights.items():
        if cid == criterion:
            out[cid] = new_wk
        elif rest > 0:
            out[cid] = w * (1.0 - new_wk) / rest
        else:
            out[cid] = 0.0
    return out


def evaluate(data: dict, delta: float = 0.2) -> Result:
    weights, normalized = _weights(data.get("criteria", []))
    alternatives = data.get("alternatives", [])
    totals, eliminated = _score_totals(alternatives, weights)
    result = Result(totals, _ranking(totals), eliminated, weights, normalized)
    if delta > 0 and len(totals) > 1:
        candidates = [a for a in alternatives if a.get("id") in totals]
        for cid in weights:
            for sign in (-1, 1):
                w2 = perturb(weights, cid, 1.0 + sign * delta)
                t2, _ = _score_totals(candidates, w2)
                result.sensitivity.append({"criterion": cid, "change": sign * delta, "winner": _ranking(t2)[0]})
    return result


def to_markdown(data: dict, result: Result) -> str:
    crit = list(result.weights)
    lines = [f"### {data.get('title', 'Matriz de decisión')}", ""]
    if result.normalized:
        lines += ["> Aviso: los pesos no sumaban 1 y se han normalizado.", ""]
    lines.append("| Alternativa | " + " | ".join(f"{c} ({result.weights[c]:.2f})" for c in crit) + " | Total |")
    lines.append("|---|" + "---|" * len(crit) + "---|")
    by_id = {a["id"]: a for a in data.get("alternatives", [])}
    for aid in result.ranking:
        scores = by_id[aid]["scores"]
        lines.append(f"| {aid} | " + " | ".join(str(scores[c]) for c in crit) + f" | **{result.totals[aid]:.2f}** |")
    if result.eliminated:
        lines += ["", "**Eliminadas por requisitos obligatorios:**"]
        lines += [f"- {aid}: {reason}" for aid, reason in result.eliminated.items()]
    if result.sensitivity:
        lines += ["", "| Criterio | Variación del peso | Ganador |", "|---|---|---|"]
        lines += [f"| {r['criterion']} | {r['change']:+.0%} | {r['winner']} |" for r in result.sensitivity]
        verdict = "FRÁGIL: el ganador cambia con variaciones de pesos" if result.fragile else "robusta frente a ±δ"
        lines += ["", f"Recomendación {verdict}."]
    return "\n".join(lines)


def main(argv: list[str] | None = None) -> int:
    if hasattr(sys.stdout, "reconfigure"):  # ERR-0002: consola/tubería cp1252 en Windows
        sys.stdout.reconfigure(encoding="utf-8")
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("input", help="Archivo JSON de entrada")
    parser.add_argument("--delta", type=float, default=0.2, help="Variación relativa de pesos (defecto 0.2)")
    parser.add_argument("--markdown", action="store_true", help="Salida en Markdown")
    parser.add_argument("--json", action="store_true", help="Salida en JSON")
    args = parser.parse_args(argv)
    with open(args.input, encoding="utf-8") as fh:
        data = json.load(fh)
    try:
        result = evaluate(data, args.delta)
    except MatrixError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        return 2
    if args.json:
        print(json.dumps({"totals": result.totals, "ranking": result.ranking, "eliminated": result.eliminated,
                          "weights": result.weights, "sensitivity": result.sensitivity,
                          "fragile": result.fragile}, ensure_ascii=False, indent=2))
    else:
        print(to_markdown(data, result))
    return 0


if __name__ == "__main__":
    sys.exit(main())
