#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
南通新东方租赁梳理 — Excel Builder v2
=====================================
从nantong-lease-audit workflow的thread输出中提取结构化数据，
生成12列Excel汇总表。K列和L列直接从rule-analyzer和template-diff步骤提取。

用法：
    python3 nantong-excel-builder.py <thread-id> <校区名> <输出xlsx路径> [文件名]
"""
import sys, os, subprocess, json, re

UWF = "/home/maggie/.hermes/node/bin/uwf"

def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True)
    return r.stdout

def get_thread_read(thread_id):
    """获取thread的完整markdown输出"""
    return run([UWF, "thread", "read", thread_id, "--quota", "200000", "--start"])

def extract_step_output(thread_text, role_name):
    """从thread read的markdown中提取某role的<output>内容"""
    pattern = rf'## Step \d+: {role_name}.*?\n<output>\n(.*?)\n</output>'
    m = re.search(pattern, thread_text, re.DOTALL)
    return m.group(1) if m else ""

def extract_frontmatter(output_text):
    """从step output中提取YAML frontmatter为dict"""
    # YAML frontmatter is between the first --- and second ---
    m = re.search(r'^---\n(.*?)\n---', output_text, re.DOTALL)
    if not m:
        # Try without leading ---
        m = re.search(r'^(.*?)\n---', output_text, re.DOTALL)
    if not m:
        return {}, output_text
    
    fm_text = m.group(1)
    body = output_text[m.end():].strip()
    
    result = {}
    current_key = None
    current_val = []
    is_multiline = False
    
    for line in fm_text.split('\n'):
        if not line.strip():
            if is_multiline:
                current_val.append('')
            continue
        
        # Check for new key: value
        km = re.match(r'^(\w[\w_]*):\s*(.*)', line)
        if km and not line.startswith(' '):
            # Save previous key
            if current_key:
                result[current_key] = '\n'.join(current_val).strip()
            current_key = km.group(1)
            val = km.group(2).strip()
            if val == '|' or val == '':
                is_multiline = True
                current_val = []
            else:
                is_multiline = False
                current_val = [val]
        elif is_multiline and current_key:
            current_val.append(line.strip())
    
    if current_key:
        result[current_key] = '\n'.join(current_val).strip()
    
    return result, body

def main():
    if len(sys.argv) < 4:
        print("用法: python3 nantong-excel-builder.py <thread-id> <校区名> <输出xlsx路径> [文件名]")
        sys.exit(1)
    
    thread_id = sys.argv[1]
    campus = sys.argv[2]
    output_path = sys.argv[3]
    filename = sys.argv[4] if len(sys.argv) > 4 else ""
    
    # 1. 获取thread完整输出
    print(f"读取thread {thread_id} ...")
    thread_text = get_thread_read(thread_id)
    
    # 2. 解析classifier
    cls_output = extract_step_output(thread_text, 'classifier')
    cls_fm, cls_body = extract_frontmatter(cls_output)
    print(f"Classifier: campus={cls_fm.get('campus','?')}, template={cls_fm.get('template_type','?')}")
    
    # 3. 解析template-diff → L列
    td_output = extract_step_output(thread_text, 'template-d')
    td_fm, td_body = extract_frontmatter(td_output)
    diff_detail = td_fm.get('diff_detail', td_body)
    print(f"Template-diff: {td_fm.get('total_diffs', '?')}处差异")
    
    # 4. 解析rule-analyzer → K列
    ra_output = extract_step_output(thread_text, 'rule-analy')
    ra_fm, ra_body = extract_frontmatter(ra_output)
    risk_detail = ra_fm.get('risk_detail', ra_body)
    term_analysis = ra_fm.get('termination_analysis', '')
    if term_analysis:
        risk_detail += '\n\n' + term_analysis
    print(f"Rule-analyzer: {ra_fm.get('risk_count', '?')}项风险")
    
    # 5. 解析data-extractor → B-J列
    de_output = extract_step_output(thread_text, 'data-extra')
    de_fm, de_body = extract_frontmatter(de_output)
    
    # 从data-extractor的output中提取B-J列
    columns = {}
    for col_letter in 'BCDEFGHIJ':
        # Try pattern "B. 文件名称：xxx" or just the value after the column letter
        pattern = rf'{col_letter}\.\s+[^：:]+[：:]\s*(.*?)(?=\n[A-L]\.\s|\nh_column|\Z)'
        m = re.search(pattern, de_body, re.DOTALL)
        if m:
            columns[col_letter] = m.group(1).strip()
        else:
            columns[col_letter] = ''
    
    # 文件名
    if filename:
        columns['B'] = filename
    elif not columns.get('B'):
        columns['B'] = cls_fm.get('ocr_text_path', '').split('/')[-1].replace('.md', '.pdf')
    
    # K列 = 法律风险（从rule-analyzer提取）
    columns['K'] = risk_detail[:8000] if risk_detail else '（法律风险分析待补充）'
    
    # L列 = 模版差异（从template-diff提取）
    columns['L'] = diff_detail[:5000] if diff_detail else '（模版差异分析待补充）'
    
    print(f"Columns: B={columns.get('B','?')[:30]} | K={len(columns.get('K',''))}chars | L={len(columns.get('L',''))}chars")
    
    # 6. 生成Excel
    import openpyxl
    from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
    
    F = Font(name='微软雅黑', size=10)
    FB = Font(name='微软雅黑', size=10, bold=True)
    TITLE_FONT = Font(name='微软雅黑', size=14, bold=True, color='FFFFFFFF')
    fill_title = PatternFill(start_color='FF8B1A2B', fill_type='solid')
    fill_sec = PatternFill(start_color='FFC0504D', fill_type='solid')
    fill_hdr = PatternFill(start_color='FFE2EFDA', fill_type='solid')
    fill_sub = PatternFill(start_color='FFF2F2F2', fill_type='solid')
    thin = Side(style='thin')
    border = Border(left=thin, right=thin, top=thin, bottom=thin)
    AL = Alignment(horizontal='left', vertical='top', wrap_text=True)
    AC = Alignment(horizontal='center', vertical='center', wrap_text=True)
    
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = campus[:31]  # sheet name max 31 chars
    
    widths = dict(A=5, B=20, C=17, D=27, E=23, F=9, G=21, H=36.33, I=34, J=8, K=50, L=35)
    for c, w in widths.items():
        ws.column_dimensions[c].width = w
    
    def merge_row(r, text, font, fill, h=None, al=AC):
        ws.merge_cells(f'A{r}:L{r}')
        cell = ws.cell(r, 1, text); cell.font = font; cell.fill = fill; cell.alignment = al
        for col in range(1, 13):
            ws.cell(r, col).fill = fill; ws.cell(r, col).border = border
        if h: ws.row_dimensions[r].height = h
    
    r = 1
    merge_row(r, f'{campus} — 租赁合同梳理', TITLE_FONT, fill_title, 30); r += 1
    
    proj = (f"物业项目：{cls_fm.get('property_address', '未知')}\n"
            f"甲方：{cls_fm.get('party_a', '未知')}\n"
            f"乙方：{cls_fm.get('party_b', '未知')}")
    merge_row(r, proj, Font(name='微软雅黑', size=10, bold=True, color='FF404040'), fill_sub, 76, AL); r += 1
    
    HDR = ['序号','文件名称','合同类型','合同当事人','租赁标的/服务范围','面积(㎡)',
           '合同期限','金额/费用','核心内容','当前状态','法律风险（站乙方立场）','与07标准模版差异']
    for ci, h in enumerate(HDR, 1):
        c = ws.cell(r, ci, h); c.font = FB; c.fill = fill_hdr; c.alignment = AC; c.border = border
    ws.row_dimensions[r].height = 30; r += 1
    
    # 数据行
    row = ['1']
    for col in 'BCDEFGHIJKL':
        row.append(columns.get(col, ''))
    
    for ci, v in enumerate(row, 1):
        c = ws.cell(r, ci, v); c.font = F
        c.alignment = AC if ci in (1,3,6,10) else AL; c.border = border
    ws.row_dimensions[r].height = 409.5
    
    ws.freeze_panes = f'A{r+1}'
    
    os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)
    wb.save(output_path)
    print(f"\n✅ 已保存: {output_path}")

if __name__ == "__main__":
    main()
