# 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("=== 压力切面彩色显示修复 ===")
print("任务目录:", task_directory)
print("切面:", surface_name)
print("保留已有模型、网格及瞬态计算状态。")

graphics = solver.settings.results.graphics
contour_collection = graphics.contour
collection_state = None
existing_names = []
contour_object = None
contour_name = None

# 1. 检查前一轮可能留下的图形对象。
try:
    collection_state = contour_collection.get_state()
    if isinstance(collection_state, dict):
        existing_names = list(collection_state.keys())
        print("当前等值线对象:", existing_names)

        old_name = "agi-pressure-cut-auto-repair"
        if old_name in collection_state:
            print("上一轮对象状态:", repr(collection_state[old_name])[:2000])
except Exception as exc:
    print("读取等值线集合失败:", repr(exc))

# 2. 优先复用已存在且可读取的最终对象。
for candidate in [
    "agi-pressure-cut-final",
    "agi-pressure-cut-final-2",
    "agi-pressure-cut-final-3",
]:
    if candidate in existing_names:
        try:
            candidate_object = contour_collection[candidate]
            candidate_object.get_state()
            contour_object = candidate_object
            contour_name = candidate
            print("复用已有对象:", contour_name)
            break
        except Exception as exc:
            print("已有对象不可用:", candidate, repr(exc))

# 只有没有可复用对象时，才创建新的独立对象。
if contour_object is None:
    for candidate in [
        "agi-pressure-cut-final",
        "agi-pressure-cut-final-2",
        "agi-pressure-cut-final-3",
    ]:
        if candidate not in existing_names:
            try:
                contour_collection.create(name=candidate)
                contour_object = contour_collection[candidate]
                contour_name = candidate
                print("已创建独立图形对象:", contour_name)
                break
            except Exception as exc:
                print("创建对象失败:", candidate, repr(exc))

if contour_object is None:
    print("未能获得可用的压力等值线对象，停止修改。")
else:
    # 3. 直接赋值，避免使用受限制的 setattr。
    try:
        contour_object.field = "pressure"
        print("压力变量设置已提交。")
    except Exception as exc:
        print("压力变量设置失败:", repr(exc))

    try:
        contour_object.filled = True
        print("填色显示设置已提交。")
    except Exception as exc:
        print("填色设置失败:", repr(exc))

    # 使用正确的 surfaces_list 属性，而不是 surfaces。
    try:
        contour_object.surfaces_list = [surface_name]
        print("切面绑定设置已提交。")
    except Exception as exc:
        print("切面绑定失败:", repr(exc))

    # 采用局部自动范围，避免全局范围压缩切面内的颜色变化。
    try:
        contour_object.range_option = {
            "option": "auto-range-on",
            "auto_range_on": {"global_range": False},
        }
        print("局部自动色标范围设置已提交。")
    except Exception as exc:
        print("局部自动范围设置失败:", repr(exc))
        try:
            contour_object.range_option = {
                "option": "auto-range-on",
                "auto_range_on": {"global_range": True},
            }
            print("已尝试使用全局自动范围作为备用。")
        except Exception as fallback_exc:
            print("备用色标设置失败:", repr(fallback_exc))

    # 4. 读取原生设置，核实修改结果。
    try:
        final_state = contour_object.get_state()
        print("最终图形状态:", repr(final_state)[:5000])

        pressure_ok = final_state.get("field") == "pressure"
        filled_ok = final_state.get("filled") is True
        surfaces_ok = (
            final_state.get("surfaces_list") == [surface_name]
        )
        range_state = final_state.get("range_option", {})
        range_ok = (
            isinstance(range_state, dict)
            and range_state.get("option") == "auto-range-on"
        )

        print("压力变量核验:", pressure_ok)
        print("填色核验:", filled_ok)
        print("切面绑定核验:", surfaces_ok)
        print("自动范围核验:", range_ok)

        if pressure_ok and filled_ok and surfaces_ok and range_ok:
            try:
                contour_object.display()
                print("已提交压力切面显示请求。")
            except Exception as exc:
                print("显示请求失败:", repr(exc))
        else:
            print("设置尚未全部通过核验，不宣称显示修复成功。")

    except Exception as exc:
        print("读取最终图形状态失败:", repr(exc))

# 5. 导出已有内部切面的压力结果，不推进计算。
print("\n=== 导出切面压力 ===")
try:
    export_result = fluentagi.export_results(
        directory=task_directory,
        fields=["pressure"],
        surfaces=[surface_name],
    )
    print("导出实际返回:", repr(export_result))

    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("\n=== 处理结束 ===")
print("未重新初始化、重建网格或推进物理时间。")
print("请依据实际状态回读与导出反馈判断结果。")