import pandas as pd
import re
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows

# 读取Markdown文件
with open('/tmp/u19_5.md', 'r', encoding='utf-8') as f:
    md_content = f.read()

wb = Workbook()

# 第一个sheet：基本信息
ws1 = wb.active
ws1.title = "基本信息"
ws1.append(["U19-5 星际通讯 剧本"])
ws1.append([])

# 提取剧情梗概
ws2 = wb.create_sheet("剧情梗概")
plot_pattern = r'<lark-table rows="6" cols="3".*?>(.*?)</lark-table>'
plot_match = re.search(plot_pattern, md_content, re.DOTALL)
if plot_match:
    plot_table = plot_match.group(1)
    rows = re.findall(r'<lark-tr>(.*?)</lark-tr>', plot_table, re.DOTALL)
    plot_data = []
    for row in rows:
        cells = re.findall(r'<lark-td[^>]*>(.*?)</lark-td>', row, re.DOTALL)
        cleaned_cells = [re.sub(r'\s+', ' ', cell.strip()) for cell in cells]
        plot_data.append(cleaned_cells)
    for r in plot_data:
        ws2.append(r)

# 第三个sheet：完整Markdown内容
ws3 = wb.create_sheet("完整剧本内容")
ws3.append(["完整剧本内容"])
ws3.append([])
lines = md_content.split('\n')
for line in lines:
    # 去除lark标签，保留纯文本
    clean_line = re.sub(r'<[^>]+>', '', line).strip()
    if clean_line:
        ws3.append([clean_line])

# 保存Excel文件
output_path = "/root/.openclaw/workspace-xiaobian/output/U19-5_星际通讯_剧本.xlsx"
wb.save(output_path)
print(f"Excel文件已保存到: {output_path}")
