#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把已抓取的 GMI 原文（markdown）排成 PDF，保留来源 URL 与抓取时间"""
import datetime
import html
import os

from playwright.sync_api import sync_playwright

SRC = '/Users/liuxinyuan/.hermes/profiles/zone-b/cache/web/www.gminsights.com-c9895d45b6.md'
OUT_DIR = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/资料/文献与专利/2025-2027/market'
URL = 'https://www.gminsights.com/industry-analysis/china-molecular-diagnostics-market'
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')

text = open(SRC, encoding='utf-8').read()
# 去掉过长的无关尾部（相关报告等），保留正文主体
cut = text.find('Related Reports')
if cut > 5000:
    text = text[:cut]

body = html.escape(text)
page_html = """<!DOCTYPE html><html><head><meta charset="utf-8"><style>
body{font-family:-apple-system,"PingFang SC",sans-serif;font-size:11px;line-height:1.55;margin:28px;color:#1b2430}
h1{font-size:16px;margin:0 0 6px}
.meta{color:#5f6b7a;font-size:10px;margin-bottom:14px;border-bottom:1px solid #ddd;padding-bottom:8px}
pre{white-space:pre-wrap;word-break:break-word;font-family:inherit;margin:0}
</style></head><body>
<h1>China Molecular Diagnostics Market Size &amp; Share 2025–2034（GMI，Report ID GMI15141）</h1>
<div class="meta">来源：%s ｜抓取时间：%s ｜说明：本 PDF 为公开页面正文的存档，用于内部核对，版权归 Global Market Insights 所有。</div>
<pre>%s</pre></body></html>""" % (URL, now, body)

tmp = '/Users/liuxinyuan/.hermes/profiles/zone-b/cache/scratch/gmi_source.html'
open(tmp, 'w', encoding='utf-8').write(page_html)
with sync_playwright() as p:
    br = p.chromium.launch(channel='chrome')
    pg = br.new_page()
    pg.goto('file://' + tmp)
    out = os.path.join(OUT_DIR, 'GMI_China_MDx_2025-2034_原文存档.pdf')
    pg.pdf(path=out, format='A4', print_background=True,
           margin={'top': '14mm', 'bottom': '14mm', 'left': '12mm', 'right': '12mm'})
    br.close()
print('PDF:', out, round(os.path.getsize(out) / 1024), 'KB', '｜正文字符', len(text))
