#!/usr/bin/env python3
"""
pdf-exporter: 将 HTML 报告导出为 PDF（通过宿主机 Chrome headless 服务渲染）
用法:
  python3 export_pdf.py --input <html_file_path> --output <pdf_file_path> [--title <标题>] [--analysis <分析文字>]
"""
import sys
import os
import re
import json
import argparse
import tempfile
import urllib.request
import urllib.error
from datetime import datetime

# Chrome PDF 服务地址（宿主机 docker0 网关）
CHROME_PDF_SERVICE = "http://10.255.0.1:9988/pdf"
WAIT_MS = 2000  # 等待 JS 渲染的时间（毫秒）

def call_chrome_pdf_service(html_content):
    """调用宿主机 Chrome headless 服务，将 HTML 转为 PDF 字节"""
    payload = json.dumps({"html": html_content, "wait_ms": WAIT_MS}).encode("utf-8")
    req = urllib.request.Request(
        CHROME_PDF_SERVICE,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST"
    )
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return resp.read(), None
    except urllib.error.HTTPError as e:
        return None, f"Chrome service HTTP error {e.code}: {e.read().decode()[:200]}"
    except urllib.error.URLError as e:
        return None, f"Chrome service unreachable: {e.reason}"
    except Exception as e:
        return None, str(e)

def build_analysis_html(analysis_text):
    """将 AI 分析文字转为 HTML 片段"""
    if not analysis_text or not analysis_text.strip():
        return ""
    lines = analysis_text.strip().split("\n")
    html_parts = ['<div style="margin-top:32px;padding:20px;background:#f0faf5;border-left:4px solid #0d6e4f;border-radius:4px;">']
    html_parts.append('<h2 style="color:#0d6e4f;font-size:16px;margin:0 0 12px 0;">AI 智能分析</h2>')
    for line in lines:
        line = line.strip()
        if not line:
            continue
        if line.startswith("## "):
            html_parts.append(f'<h3 style="color:#0d6e4f;font-size:14px;margin:12px 0 6px 0;">{line[3:]}</h3>')
        elif line.startswith("- "):
            html_parts.append(f'<p style="margin:4px 0 4px 12px;color:#333;">• {line[2:]}</p>')
        else:
            html_parts.append(f'<p style="margin:6px 0;color:#333;">{line}</p>')
    now = datetime.now().strftime("%Y-%m-%d %H:%M")
    html_parts.append(f'<p style="margin-top:16px;color:#999;font-size:12px;">以上分析由 AI 自动生成，仅供参考。生成时间：{now}</p>')
    html_parts.append('</div>')
    return "\n".join(html_parts)

def inject_analysis_into_html(html_content, analysis_text):
    """将 AI 分析章节注入到 HTML body 末尾"""
    analysis_html = build_analysis_html(analysis_text)
    if not analysis_html:
        return html_content
    # 在 </body> 前插入
    if "</body>" in html_content.lower():
        idx = html_content.lower().rfind("</body>")
        return html_content[:idx] + analysis_html + html_content[idx:]
    else:
        return html_content + analysis_html

def generate_pdf(input_path, output_path, title=None, analysis_text=None):
    """读取 HTML，注入分析，调用 Chrome 服务生成 PDF"""
    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}"}

    # 注入 AI 分析
    has_analysis = bool(analysis_text and analysis_text.strip())
    if has_analysis:
        html_content = inject_analysis_into_html(html_content, analysis_text)

    # 如果有 title，注入到 <title> 标签
    if title:
        if re.search(r'<title[^>]*>', html_content, re.IGNORECASE):
            html_content = re.sub(r'<title[^>]*>.*?</title>', f'<title>{title}</title>',
                                  html_content, flags=re.IGNORECASE | re.DOTALL)
        else:
            html_content = html_content.replace('<head>', f'<head><title>{title}</title>', 1)

    # 调用 Chrome 服务
    pdf_bytes, err = call_chrome_pdf_service(html_content)
    if err:
        return {"status": "error", "message": f"Chrome PDF 服务错误: {err}"}

    # 保存 PDF
    os.makedirs(os.path.dirname(output_path) if os.path.dirname(output_path) else ".", exist_ok=True)
    try:
        with open(output_path, "wb") as f:
            f.write(pdf_bytes)
    except Exception as e:
        return {"status": "error", "message": f"保存 PDF 失败: {e}"}

    file_size = os.path.getsize(output_path)
    return {
        "status": "success",
        "message": "PDF 导出成功" + ("（含 AI 分析）" if has_analysis else ""),
        "output_path": output_path,
        "file_size_kb": round(file_size / 1024, 1),
        "chinese_font": True,
        "has_analysis": has_analysis,
        "renderer": "chrome-headless"
    }

def main():
    parser = argparse.ArgumentParser(description="将 HTML 报告导出为 PDF（Chrome headless 渲染）")
    parser.add_argument("--input",    required=True,  help="输入 HTML 文件路径")
    parser.add_argument("--output",   required=True,  help="输出 PDF 文件路径")
    parser.add_argument("--title",    default=None,   help="PDF 标题（可选）")
    parser.add_argument("--analysis", default=None,   help="AI 分析内容（可选），支持 Markdown 格式")
    args = parser.parse_args()
    result = generate_pdf(args.input, args.output, args.title, args.analysis)
    print(json.dumps(result, ensure_ascii=False))
    sys.exit(0 if result["status"] == "success" else 1)

if __name__ == "__main__":
    main()
