# Use the existing connected PyFluent variable solver.
# Continue with the complete executable script here.

task_directory = r"C:\Users\13977\AppData\Local\FluentAGI\data\runs\20261020-124717-f33d8b"
surface_name = "agi-section-e3e1d5"

print("=== Fluent：内部切面彩色云图优化与图形接口诊断 ===")
print("原任务目录:", task_directory)
print("复用现有求解器、网格、计算结果和内部切面。")
print("本轮不初始化、不重载模型、不推进物理时间。")


def show_value(label, value, limit=2400):
    text_value = repr(value)
    if len(text_value) > limit:
        text_value = text_value[:limit] + "...[截断]"
    print(label, "=", text_value)


def inspect_node(label, node):
    print("\n--- 图形节点：", label, "---")
    if node is None:
        print("节点不存在或当前版本未公开此接口。")
        return

    print("类型:", type(node).__name__)

    try:
        names = sorted(
            name for name in dir(node)
            if not name.startswith("_")
        )
        keywords = (
            "contour", "pathline", "stream", "vector",
            "color", "range", "scale", "surface", "field",
            "display", "view", "legend", "mesh"
        )
        matched = [
            name for name in names
            if any(word in name.lower() for word in keywords)
        ]
        print("相关公开属性/方法:", matched[:100])
    except Exception as exc:
        print("属性检查失败:", repr(exc))

    try:
        getter = getattr(node, "get_state", None)
        if callable(getter):
            state = getter()
            show_value("当前原生设置", state)
        else:
            print("该节点未公开可调用的 get_state。")
    except Exception as exc:
        print("原生状态读取失败:", repr(exc))


# 1. 查询当前模型是否有效；避免在空模型上读取结果设置。
active = None

for owner_name, owner in [
    ("fluentagi", fluentagi),
    ("solver", solver)
]:
    try:
        checker = getattr(owner, "is_active", None)
        if callable(checker):
            active = bool(checker())
            print(owner_name + ".is_active() =", active)
            break
    except Exception as exc:
        print(owner_name, "活动状态检查失败:", repr(exc))

if active is False:
    raise RuntimeError(
        "当前求解器未报告有效活动模型。停止后处理，"
        "不自动恢复、重载或初始化。"
    )

if active is None:
    print("运行时未暴露可调用的 is_active；")
    print("当前任务上下文报告 model_active=True，继续尝试只读检查。")

# 2. 检查实际存在的图形接口，不假定版本具有特定的流线接口。
graphics = None

try:
    graphics = solver.settings.results.graphics
    print("\n已取得 solver.settings.results.graphics。")
except Exception as exc:
    print("读取图形设置根节点失败:", repr(exc))

if graphics is not None:
    inspect_node("graphics 根节点", graphics)

    # 按 FluentAGI 约定检查视图和网格图形接口。
    for name in ["views", "mesh"]:
        try:
            node = getattr(graphics, name)
            inspect_node("graphics." + name, node)
        except Exception as exc:
            print("读取 graphics." + name + " 失败:", repr(exc))

    # 仅检查真实公开的相关节点，不对未知接口写入设置。
    try:
        public_names = [
            name for name in dir(graphics)
            if not name.startswith("_")
        ]
        keywords = (
            "contour", "pathline", "stream",
            "vector", "scene", "surface"
        )
        candidates = [
            name for name in public_names
            if any(word in name.lower() for word in keywords)
        ]

        print("\n发现的候选图形接口:", candidates[:100])

        for name in candidates[:12]:
            try:
                node = getattr(graphics, name)
                if callable(node):
                    print("接口", name, "是可调用对象，暂不执行。")
                else:
                    inspect_node("graphics." + name, node)
            except Exception as exc:
                print("检查候选接口", name, "失败:", repr(exc))

    except Exception as exc:
        print("图形接口枚举失败:", repr(exc))

# 3. 复用之前成功创建的内部切面。
# 同时导出压力和速度大小，便于比较两种物理量的空间变化。
# 不重新创建切面，也不重复生成会推进计算时间的动画。
print("\n=== 导出内部切面结果 ===")
print("切面:", surface_name)

export_result = None

try:
    export_result = fluentagi.export_results(
        directory=task_directory,
        fields=["pressure", "velocity-magnitude"],
        surfaces=[surface_name]
    )

    print("导出适配器返回:")
    show_value("export_results", export_result, 5000)

    if isinstance(export_result, dict):
        print("导出状态:", export_result.get("status", "未提供"))
        print("输出目录:", export_result.get("directory", "未提供"))
        print(
            "收敛验证:",
            export_result.get("convergence_verified", "未提供")
        )

except Exception as exc:
    print("切面云图导出失败:", repr(exc))
    print("保留现有模型和结果，不盲目重试。")

# 4. 汇总本轮实际执行范围。
print("\n=== 本轮执行范围 ===")
print("请求字段: pressure、velocity-magnitude")
print("请求范围: 现有内部切面")
print("未调用初始化、网格生成或时间推进。")
print("未修改未知图形接口，也未伪造色标范围。")
print("请依据实际返回的图形接口和导出文件继续调整色标。")