#!/usr/bin/env python3
"""Par requerido por rueda motriz de Atlas X1 (base mecanum de cuatro ruedas), modelo cuasiestático.

Uso:
    python wheel_torque.py caso.json [--markdown]

Entrada JSON (todas las magnitudes físicas son obligatorias; no hay valores por defecto «inventados»):
    {
      "mass_kg": 1.8, "wheel_radius_m": 0.04, "driven_wheels": 4,
      "max_slope_deg": 10, "rolling_resistance": 0.03, "max_accel_mps2": 0.5,
      "mecanum_efficiency": 0.6, "load_factor": 1.2, "safety_factor": 1.5,
      "friction_coefficient": 0.6,                 (opcional: comprobación de deslizamiento)
      "max_speed_mps": 0.4,                        (opcional: rpm de rueda)
      "gear_ratio": 30, "gear_efficiency": 0.8,    (opcional: par en el eje del motor)
      "motor_continuous_torque_Nm": 0.05           (opcional: utilización, en el eje del motor)
    }

Modelo: F = m·g·(sin θ + C_rr·cos θ) + m·a reparte la fuerza de tracción entre las ruedas motrices, multiplicada por
el factor de reparto no uniforme; las pérdidas de los rodillos mecanum se representan con una eficiencia (0, 1] que es
una HIPÓTESIS a validar experimentalmente. Resultado de nivel «teorico».
"""
from __future__ import annotations

import argparse
import json
import math
import sys

G = 9.80665  # m/s², gravedad estándar
NM_TO_KGCM = 1.0 / (G * 0.01)  # 1 N·m = 10,197 kg·cm

REQUIRED = ("mass_kg", "wheel_radius_m", "driven_wheels", "max_slope_deg", "rolling_resistance", "max_accel_mps2",
            "mecanum_efficiency", "load_factor", "safety_factor")


def analyze(case: dict) -> dict:
    missing = [k for k in REQUIRED if k not in case]
    if missing:
        raise ValueError(f"Faltan campos obligatorios: {', '.join(missing)}")
    m, r, n = float(case["mass_kg"]), float(case["wheel_radius_m"]), int(case["driven_wheels"])
    eta, kf, fs = float(case["mecanum_efficiency"]), float(case["load_factor"]), float(case["safety_factor"])
    if m <= 0 or r <= 0 or n <= 0:
        raise ValueError("mass_kg, wheel_radius_m y driven_wheels deben ser positivos")
    if not 0 < eta <= 1:
        raise ValueError("mecanum_efficiency debe estar en (0, 1]")
    if kf < 1 or fs < 1:
        raise ValueError("load_factor y safety_factor deben ser >= 1")
    th = math.radians(float(case["max_slope_deg"]))
    f_slope = m * G * math.sin(th)
    f_roll = m * G * float(case["rolling_resistance"]) * math.cos(th)
    f_acc = m * float(case["max_accel_mps2"])
    f_total = f_slope + f_roll + f_acc
    f_wheel = f_total / n * kf
    tau_static = f_wheel * r / eta
    tau_req = tau_static * fs
    out = {
        "forces_N": {"pendiente": f_slope, "rodadura": f_roll, "aceleracion": f_acc, "total": f_total, "por_rueda": f_wheel},
        "wheel_torque_Nm": tau_static, "required_wheel_torque_Nm": tau_req,
        "required_wheel_torque_kgcm": tau_req * NM_TO_KGCM, "warnings": [],
    }
    if "friction_coefficient" in case:
        normal = m * G * math.cos(th) / 4.0 * kf
        limit = float(case["friction_coefficient"]) * normal
        out["traction_limit_N"] = limit
        if f_wheel > limit:
            out["warnings"].append(f"La fuerza por rueda ({f_wheel:.2f} N) supera el límite de adherencia ({limit:.2f} N): deslizamiento")
    if "max_speed_mps" in case:
        out["wheel_rpm"] = float(case["max_speed_mps"]) / (2 * math.pi * r) * 60.0
    if "gear_ratio" in case:
        ratio = float(case["gear_ratio"])
        geff = float(case.get("gear_efficiency", 1.0))
        if ratio <= 0 or not 0 < geff <= 1:
            raise ValueError("gear_ratio > 0 y gear_efficiency en (0, 1]")
        out["required_motor_torque_Nm"] = tau_req / (ratio * geff)
        if "wheel_rpm" in out:
            out["motor_rpm"] = out["wheel_rpm"] * ratio
        if "motor_continuous_torque_Nm" in case:
            cont = float(case["motor_continuous_torque_Nm"])
            out["motor_utilization"] = out["required_motor_torque_Nm"] / cont
            if out["motor_utilization"] > 1:
                out["warnings"].append("El par requerido supera el par continuo del motor")
    return out


def to_markdown(res: dict) -> str:
    f = res["forces_N"]
    rows = [
        "| Magnitud | Valor |", "|---|---|",
        f"| Fuerza por pendiente | {f['pendiente']:.3f} N |",
        f"| Fuerza de rodadura | {f['rodadura']:.3f} N |",
        f"| Fuerza de aceleración | {f['aceleracion']:.3f} N |",
        f"| Fuerza por rueda (con reparto) | {f['por_rueda']:.3f} N |",
        f"| Par por rueda (sin factor de seguridad) | {res['wheel_torque_Nm']:.4f} N·m |",
        f"| **Par requerido por rueda** | **{res['required_wheel_torque_Nm']:.4f} N·m ({res['required_wheel_torque_kgcm']:.2f} kg·cm)** |",
    ]
    for key, label, unit in (("wheel_rpm", "Velocidad de rueda", "rpm"), ("required_motor_torque_Nm", "Par requerido en el motor", "N·m"),
                             ("motor_rpm", "Velocidad del motor", "rpm"), ("motor_utilization", "Utilización del motor", "")):
        if key in res:
            rows.append(f"| {label} | {res[key]:.3f} {unit} |")
    text = "\n".join(rows) + "\n\n_Resultado teórico (modelo cuasiestático); validar con el banco de una rueda._\n"
    for w in res["warnings"]:
        text += f"\n> Aviso: {w}"
    return text


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")
    p = argparse.ArgumentParser(description="Par requerido por rueda mecanum")
    p.add_argument("case", help="archivo JSON del caso")
    p.add_argument("--markdown", action="store_true")
    a = p.parse_args(argv)
    try:
        with open(a.case, encoding="utf-8") as fh:
            res = analyze(json.load(fh))
    except (OSError, ValueError, json.JSONDecodeError) as e:
        print(f"Error: {e}", file=sys.stderr)
        return 2
    print(to_markdown(res) if a.markdown else json.dumps(res, indent=2, ensure_ascii=False))
    return 0


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