# -*- coding: utf-8 -*-
"""
探测 Motor-CAD AFM 轴向力图名/变量名 (第2轮)
============================================
依据: MotorCAD.exe (v261) UTF-16 字符串中有 "_Axial_Force_Rotor" /
"_Axial_Force_Stator" 后缀 (前缀运行时拼接), 以及 GUI 显示名 "Axial Force"。
一次求解后穷举前缀组合, 用 get_magnetic_graph / get_variable 逐个试,
命中与否全部如实记录。

用法: python axial_probe.py [--quit]
"""
import json
import os
import sys
import time

BASE = os.path.dirname(os.path.abspath(__file__))
MOT_SRC = os.path.join(BASE, "MARS-12S10P_SSSR_D76-C150_V5.0-0819.mot")
OUT_DIR = os.path.join(BASE, "output_motorcad")

PREFIXES = ["", "OC", "OC_", "OC ", "OL", "OL_", "OL ", "Load", "Load_",
            "OnLoad_", "OnLoad", "OpenCircuit_", "OpenCircuit", "NoLoad_",
            "Th1_", "Th1", "1_", "Transient_", "Static_"]
SUFFIXES = ["Axial_Force_Rotor", "Axial_Force_Stator"]
EXTRA_GRAPHS = [
    "Axial_Force", "Axial Force", "Axial Force Rotor", "Axial Force Stator",
    "Axial Force (Rotor)", "Axial Force (Stator)", "AxialForceRotor",
    "AxialForceStator", "Fz_Rotor_OL_Lumped", "Fz_Stator_OL_Lumped",
    "Fz_Rotor_OC_Lumped", "Fz_Stator_OC_Lumped", "Fa_Rotor_OL_Lumped",
    "Ft_Rotor_OL_Lumped",  # 已知径向机存在的命名, 作对照验证探测方法本身
    "TorqueVsAngle",       # 已知图, 验证 get_magnetic_graph 可用
]
VAR_CANDS = (["AxialForceRotor", "AxialForceStator"] +
             [p + s for p in ("", "OC_", "OL_", "Load_") for s in SUFFIXES])


def stats(ys):
    if not ys:
        return None
    return {"mean": sum(ys) / len(ys), "min": min(ys), "max": max(ys),
            "pk2pk": max(ys) - min(ys), "n": len(ys)}


def main(argv):
    quit_after = "--quit" in argv
    os.makedirs(OUT_DIR, exist_ok=True)
    ts = time.strftime("%m%d_%H%M%S")

    from ansys.motorcad.core import MotorCAD
    print("启动 Motor-CAD (前台) ...")
    mc = MotorCAD()
    results = {"when": ts, "probe_round": 2}
    try:
        mc.load_from_file(MOT_SRC)
        out_mot = os.path.join(OUT_DIR, "MARS_SSSR_probe_%s.mot" % ts)
        mc.save_to_file(out_mot)
        results["work_mot"] = out_mot

        # 电流口径侦察 (上轮空载疑似未生效: CurrentDefinition=1)
        cur = {}
        for n in ["CurrentDefinition", "PeakCurrent", "RMSCurrent",
                  "Imax", "Irms", "RMS_Current", "LineCurrent"]:
            try:
                cur[n] = mc.get_variable(n)
            except Exception:
                cur[n] = "<not found>"
        results["current_vars"] = cur
        print("电流相关变量: %s" % json.dumps(cur, ensure_ascii=False))

        for var in ["ElectromagneticForcesCalc_Load",
                    "ElectromagneticForcesCalc_OC"]:
            mc.set_variable(var, True)

        print("单次求解 (负载点, OC/Load 力同时计算) ...")
        t0 = time.time()
        mc.do_magnetic_calculation()
        print("  耗时 %.1f s" % (time.time() - t0))

        # ---- 图名穷举 ----
        graph_names = ([p + s for p in PREFIXES for s in SUFFIXES]
                       + EXTRA_GRAPHS)
        hits, misses = {}, []
        for g in graph_names:
            try:
                x, y = mc.get_magnetic_graph(g)
                hits[g] = {"stats": stats(list(y)), "x0": x[0], "x_end": x[-1],
                           "x": list(x), "y": list(y)}
                print("  [命中] %s: %s" % (g, hits[g]["stats"]))
            except Exception:
                misses.append(g)
        results["graph_hits"] = {k: {kk: vv for kk, vv in v.items()
                                     if kk != "x"} for k, v in hits.items()}
        results["graph_hits_full"] = hits
        results["graph_misses"] = misses
        print("图名: 命中 %d / 未中 %d" % (len(hits), len(misses)))

        # ---- 输出变量穷举 ----
        var_hits = {}
        for n in VAR_CANDS:
            try:
                var_hits[n] = mc.get_variable(n)
                print("  [变量命中] %s = %s" % (n, var_hits[n]))
            except Exception:
                pass
        results["variable_hits"] = var_hits

        res_path = os.path.join(OUT_DIR, "probe_results_%s.json" % ts)
        with open(res_path, "w", encoding="utf-8") as f:
            json.dump(results, f, ensure_ascii=False, indent=2)
        print("RESULTS: %s" % res_path)
        return 0
    finally:
        if quit_after:
            try:
                mc.quit()
            except Exception:
                pass
        else:
            print("[提示] Motor-CAD 保持前台打开供检查。")


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
