# -*- coding: utf-8 -*-
# 将排查步骤栏从输入框下方移动到人员信息栏下方、消息区域上方

filepath = r"C:\Users\simon\WorkBuddy\2026-05-21-16-57-26\agent-workspace-v5_3.html"

with open(filepath, 'r', encoding='utf-8') as f:
    content = f.read()

# 1. 找到排查步骤栏的起始和结束位置
ts_start_marker = '<div class="troubleshoot-bar" id="tsBar">'
ts_start_idx = content.find(ts_start_marker)

if ts_start_idx == -1:
    print("ERROR: 找不到排查步骤栏起始标记")
exit(1)

# 找到对应的结束 </div>
pos = ts_start_idx
# 跳过起始标签所在的行
pos = content.find('\n', pos) + 1

depth = 0
ts_end_idx = -1

while pos < len(content):
    next_div = content.find('<div', pos)
    next_end_div = content.find('</div>', pos)

    if next_end_div == -1:
        break

    if next_div != -1 and next_div < next_end_div:
        depth += 1
        pos = next_div + 1
    else:
        if depth == 0:
            ts_end_idx = next_end_div + len('</div>')
            break
        depth -= 1
        pos = next_end_div + len('</div>')

if ts_end_idx == -1:
    print("ERROR: 找不到排查步骤栏的闭合标签")
exit(1)

ts_bar_html = content[ts_start_idx:ts_end_idx]

print(f"找到排查步骤栏：位置 {ts_start_idx} 到 {ts_end_idx}")
print(f"长度：{len(ts_bar_html)} 字符")

# 2. 从原位置删除排查步骤栏
content_without_ts = content[:ts_start_idx] + content[ts_end_idx:]

# 3. 找到插入位置：在 user-detail-panel 的 </div> 之后，chat-messages 之前
# 目标标记
target_marker = '</div>\n    \n    <!-- Chat -->\n      <div class="chat-messages">'
target_idx = content_without_ts.find(target_marker)

if target_idx == -1:
    # 尝试其他格式
    target_marker2 = '</div>\n    \n    <!-- Chat -->'
    target_idx = content_without_ts.find(target_marker2)
    if target_idx == -1:
        print("ERROR: 找不到目标插入位置（user-detail-panel 闭合后）")
        # 调试：看看 user-detail-panel 附近的内容
        udp_start = content_without_ts.find('<div class="user-detail-panel">')
        if udp_start != -1:
            print("user-detail-panel 附近内容：")
            print(repr(content_without_ts[udp_start:udp_start+500]))
        exit(1)
    # 找到 target_idx 后，需要定位到 <!-- Chat --> 之后的 <div class="chat-messages"> 之前
    # 重新计算
    insert_pos = content_without_ts.find('</div>\n    \n    <!-- Chat -->')
    if insert_pos == -1:
        print("ERROR: 找不到准确插入点")
        exit(1)
    insert_pos = content_without_ts.find('>', insert_pos) + 1
    # 现在 insert_pos 指向 <!-- Chat --> 之后的位置
else:
    insert_pos = target_idx + len('</div>')

# 4. 在 insert_pos 处插入排查步骤栏
new_content = content_without_ts[:insert_pos] + '\n    ' + ts_bar_html.strip() + '\n    ' + content_without_ts[insert_pos:]

# 5. 写回文件
with open(filepath, 'w', encoding='utf-8') as f:
    f.write(new_content)

print("✅ 排查步骤栏已移动到人员信息栏下方、消息区域上方")
print(f"原位置：{ts_start_idx}")
print(f"新位置：{insert_pos}")
