#!/usr/bin/env python3
"""
pdf-exporter: 将 HTML 报告导出为支持中文的 PDF 文件
用法:
  python3 export_pdf.py --input <html_file_path> --output <pdf_file_path> [--title <标题>]

依赖:
  - reportlab (已安装于 /workspace/.local/lib/python3.11/site-packages)
  - 中文字体: /workspace/skills/pdf-exporter/fonts/wqy-microhei.ttc
"""

import sys
import os
import re
import json
import argparse
import html as html_module

# 将 reportlab 安装路径加入 sys.path
sys.path.insert(0, '/workspace/.local/lib/python3.11/site-packages')

try:
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import A4
    from reportlab.lib.units import mm
    from reportlab.lib import colors
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.platypus import (
        SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
        HRFlowable, KeepTogether
    )
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT
except ImportError as e:
    print(json.dumps({"status": "error", "message": f"reportlab 未安装: {e}"}))
    sys.exit(1)

# ── 字体注册 ──────────────────────────────────────────────────────────────────
SKILL_DIR  = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FONT_PATH  = os.path.join(SKILL_DIR, 'fonts', 'wqy-microhei.ttc')
FONT_NAME  = 'WQYMicroHei'
FONT_BOLD  = 'WQYMicroHei'   # TTC 字体用同一字体名，通过 bold 参数区分

def register_chinese_font():
    """注册中文字体，失败时回退到 Helvetica 并打印警告"""
    if not os.path.exists(FONT_PATH):
        sys.stderr.write(f"[WARNING] 中文字体文件不存在: {FONT_PATH}\n")
        sys.stderr.write("[WARNING] 将使用默认字体，中文可能显示为方块\n")
        return False
    try:
        pdfmetrics.registerFont(TTFont(FONT_NAME, FONT_PATH))
        return True
    except Exception as e:
        sys.stderr.write(f"[WARNING] 字体注册失败: {e}\n")
        return False

# ── HTML 文本清理 ─────────────────────────────────────────────────────────────
def strip_html_tags(text):
    """移除 HTML 标签，保留纯文本"""
    text = re.sub(r'<style[^>]*>.*?</style>', '', text, flags=re.DOTALL | re.IGNORECASE)
    text = re.sub(r'<script[^>]*>.*?</script>', '', text, flags=re.DOTALL | re.IGNORECASE)
    text = re.sub(r'<[^>]+>', '', text)
    text = html_module.unescape(text)
    return text.strip()

def extract_html_sections(html_content):
    """从 HTML 中提取标题、段落、表格等结构化内容"""
    sections = []

    # 提取 <title>
    m = re.search(r'<title[^>]*>(.*?)</title>', html_content, re.IGNORECASE | re.DOTALL)
    if m:
        sections.append({'type': 'title', 'text': strip_html_tags(m.group(1))})

    # 提取 body 内容
    body_m = re.search(r'<body[^>]*>(.*?)</body>', html_content, re.IGNORECASE | re.DOTALL)
    body = body_m.group(1) if body_m else html_content

    # 逐段提取 h1~h4、p、table
    pattern = re.compile(
        r'(<h[1-4][^>]*>.*?</h[1-4]>|<p[^>]*>.*?</p>|<table[^>]*>.*?</table>)',
        re.IGNORECASE | re.DOTALL
    )
    for match in pattern.finditer(body):
        tag_html = match.group(1)
        tag_name = re.match(r'<(\w+)', tag_html).group(1).lower()

        if tag_name in ('h1', 'h2', 'h3', 'h4'):
            level = int(tag_name[1])
            text = strip_html_tags(tag_html).strip()
            if text:
                sections.append({'type': 'heading', 'level': level, 'text': text})

        elif tag_name == 'p':
            text = strip_html_tags(tag_html).strip()
            if text and len(text) > 1:
                sections.append({'type': 'paragraph', 'text': text})

        elif tag_name == 'table':
            rows_data = []
            for row_m in re.finditer(r'<tr[^>]*>(.*?)</tr>', tag_html, re.IGNORECASE | re.DOTALL):
                row_html = row_m.group(1)
                cells = [strip_html_tags(c).strip()
                         for c in re.findall(r'<t[hd][^>]*>(.*?)</t[hd]>', row_html,
                                             re.IGNORECASE | re.DOTALL)]
                if cells:
                    rows_data.append(cells)
            if rows_data:
                sections.append({'type': 'table', 'rows': rows_data})

    return sections

# ── PDF 生成 ──────────────────────────────────────────────────────────────────
def build_styles(has_chinese_font):
    """构建段落样式"""
    base_font = FONT_NAME if has_chinese_font else 'Helvetica'
    styles = getSampleStyleSheet()

    custom = {
        'doc_title': ParagraphStyle(
            'DocTitle',
            fontName=base_font,
            fontSize=20,
            leading=28,
            spaceAfter=8,
            alignment=TA_CENTER,
            textColor=colors.HexColor('#1a1a2e'),
        ),
        'h1': ParagraphStyle(
            'H1', fontName=base_font, fontSize=16, leading=22,
            spaceBefore=14, spaceAfter=6,
            textColor=colors.HexColor('#1677FF'),
            borderPadding=(0, 0, 4, 0),
        ),
        'h2': ParagraphStyle(
            'H2', fontName=base_font, fontSize=13, leading=18,
            spaceBefore=10, spaceAfter=4,
            textColor=colors.HexColor('#333333'),
        ),
        'h3': ParagraphStyle(
            'H3', fontName=base_font, fontSize=11, leading=16,
            spaceBefore=8, spaceAfter=3,
            textColor=colors.HexColor('#555555'),
        ),
        'h4': ParagraphStyle(
            'H4', fontName=base_font, fontSize=10, leading=14,
            spaceBefore=6, spaceAfter=2,
            textColor=colors.HexColor('#777777'),
        ),
        'body': ParagraphStyle(
            'Body', fontName=base_font, fontSize=10, leading=16,
            spaceAfter=6, textColor=colors.HexColor('#333333'),
        ),
        'table_header': ParagraphStyle(
            'TableHeader', fontName=base_font, fontSize=9, leading=13,
            alignment=TA_CENTER, textColor=colors.white,
        ),
        'table_cell': ParagraphStyle(
            'TableCell', fontName=base_font, fontSize=9, leading=13,
            alignment=TA_LEFT, textColor=colors.HexColor('#333333'),
        ),
    }
    return custom

def sections_to_flowables(sections, styles, page_width):
    """将结构化内容转换为 reportlab flowables"""
    flowables = []
    usable_width = page_width - 40 * mm

    heading_styles = {1: styles['h1'], 2: styles['h2'], 3: styles['h3'], 4: styles['h4']}

    for sec in sections:
        if sec['type'] == 'title':
            flowables.append(Paragraph(sec['text'], styles['doc_title']))
            flowables.append(HRFlowable(width='100%', thickness=2,
                                        color=colors.HexColor('#1677FF'), spaceAfter=12))

        elif sec['type'] == 'heading':
            level = sec.get('level', 2)
            style = heading_styles.get(level, styles['h2'])
            flowables.append(Paragraph(sec['text'], style))
            if level == 1:
                flowables.append(HRFlowable(width='100%', thickness=1,
                                            color=colors.HexColor('#e0e0e0'), spaceAfter=4))

        elif sec['type'] == 'paragraph':
            text = sec['text']
            # 过滤掉纯空白或无意义内容
            if len(text.strip()) > 2:
                flowables.append(Paragraph(text, styles['body']))

        elif sec['type'] == 'table':
            rows = sec['rows']
            if not rows:
                continue

            # 均分列宽
            col_count = max(len(r) for r in rows)
            col_width = usable_width / col_count

            # 将每个单元格转为 Paragraph
            table_data = []
            for i, row in enumerate(rows):
                # 补齐列数
                while len(row) < col_count:
                    row.append('')
                if i == 0:
                    cell_style = styles['table_header']
                else:
                    cell_style = styles['table_cell']
                table_data.append([Paragraph(str(cell), cell_style) for cell in row])

            t = Table(table_data, colWidths=[col_width] * col_count, repeatRows=1)
            t.setStyle(TableStyle([
                # 表头样式
                ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1677FF')),
                ('TEXTCOLOR',  (0, 0), (-1, 0), colors.white),
                ('FONTSIZE',   (0, 0), (-1, 0), 9),
                ('ALIGN',      (0, 0), (-1, 0), 'CENTER'),
                ('VALIGN',     (0, 0), (-1, -1), 'MIDDLE'),
                # 数据行交替背景
                ('ROWBACKGROUNDS', (0, 1), (-1, -1),
                 [colors.white, colors.HexColor('#f5f8ff')]),
                # 边框
                ('GRID',       (0, 0), (-1, -1), 0.5, colors.HexColor('#d0d0d0')),
                ('LINEBELOW',  (0, 0), (-1, 0), 1.5, colors.HexColor('#1677FF')),
                # 内边距
                ('TOPPADDING',    (0, 0), (-1, -1), 5),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
                ('LEFTPADDING',   (0, 0), (-1, -1), 6),
                ('RIGHTPADDING',  (0, 0), (-1, -1), 6),
            ]))
            flowables.append(t)
            flowables.append(Spacer(1, 8))

    return flowables

def generate_pdf(input_path, output_path, title=None):
    """主函数：读取 HTML，生成 PDF"""
    # 注册中文字体
    has_chinese_font = register_chinese_font()

    # 读取 HTML
    try:
        with open(input_path, 'r', encoding='utf-8') as f:
            html_content = f.read()
    except Exception as e:
        return {"status": "error", "message": f"读取 HTML 文件失败: {e}"}

    # 提取结构
    sections = extract_html_sections(html_content)

    # 如果有外部标题，插入到最前面
    if title:
        sections.insert(0, {'type': 'title', 'text': title})

    # 构建样式
    styles = build_styles(has_chinese_font)

    # 创建文档
    os.makedirs(os.path.dirname(output_path) if os.path.dirname(output_path) else '.', exist_ok=True)
    doc = SimpleDocTemplate(
        output_path,
        pagesize=A4,
        leftMargin=20 * mm,
        rightMargin=20 * mm,
        topMargin=20 * mm,
        bottomMargin=20 * mm,
        title=title or '数据分析报告',
        author='OpenClaw Agent',
    )

    page_width = A4[0]
    flowables = sections_to_flowables(sections, styles, page_width)

    if not flowables:
        return {"status": "error", "message": "HTML 内容为空，无法生成 PDF"}

    try:
        doc.build(flowables)
    except Exception as e:
        return {"status": "error", "message": f"PDF 生成失败: {e}"}

    file_size = os.path.getsize(output_path)
    return {
        "status": "success",
        "message": "PDF 导出成功",
        "output_path": output_path,
        "file_size_kb": round(file_size / 1024, 1),
        "chinese_font": has_chinese_font,
        "sections_count": len(sections),
    }

# ── 入口 ──────────────────────────────────────────────────────────────────────
def main():
    parser = argparse.ArgumentParser(description='将 HTML 报告导出为支持中文的 PDF')
    parser.add_argument('--input',  required=True, help='输入 HTML 文件路径')
    parser.add_argument('--output', required=True, help='输出 PDF 文件路径')
    parser.add_argument('--title',  default=None,  help='PDF 标题（可选）')
    args = parser.parse_args()

    result = generate_pdf(args.input, args.output, args.title)
    print(json.dumps(result, ensure_ascii=False))
    sys.exit(0 if result['status'] == 'success' else 1)

if __name__ == '__main__':
    main()
