#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
市场情报 Markdown → 自包含 HTML（白蓝科技风 + 品牌页眉页脚）

用法：
    /usr/bin/python3 脚本/market_intel_html.py 数据/market_intel/20261102_市场情报.md
产物：
    同目录同名 .html（并同步 latest.html 若源为日期版）
"""
import html as H
import os
import re
import sys

BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE, '脚本'))
import brand_kit as BK  # noqa: E402

CSS = """
:root{--pri:#1a73e8;--pri-d:#0d47a1;--ink:#202124;--sub:#5f6368;--line:#e3e8ef;--bg:#f5f7fa}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--ink);
 font:16px/1.85 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif}
.wrap{max-width:1080px;margin:26px auto 60px;padding:0 18px}
.card{background:#fff;border:1px solid var(--line);border-radius:14px;
 box-shadow:0 2px 14px rgba(13,71,161,.06);padding:34px 42px 42px}
.doc-title{font-size:27px;line-height:1.35;margin:0 0 6px;color:var(--pri-d);font-weight:800}
.meta{display:flex;flex-wrap:wrap;gap:8px;margin:14px 0 6px}
.chip{font-size:12.5px;color:#1554a8;background:#e8f1fd;border:1px solid #cfe1fb;
 border-radius:999px;padding:4px 12px;white-space:nowrap}
h2{font-size:20px;margin:34px 0 12px;padding-left:12px;border-left:5px solid var(--pri);
 color:#123a6b;line-height:1.5}
h3{font-size:16.5px;margin:22px 0 8px;color:#1554a8}
p{margin:10px 0}
ul,ol{margin:10px 0 14px;padding-left:24px}
li{margin:7px 0}
blockquote{margin:16px 0;padding:14px 18px;background:#f2f7ff;
 border-left:4px solid #9dc2f5;border-radius:8px;color:#33475b;font-size:14.5px}
blockquote p{margin:6px 0}
hr{border:none;border-top:1px dashed #cbd6e4;margin:30px 0}
code{background:#eef2f7;border-radius:4px;padding:1px 5px;font-size:13px;
 font-family:ui-monospace,Menlo,Consolas,monospace;color:#b3261e}
strong{color:#0d2a52}
.toc{background:#fbfdff;border:1px solid #e1ebf8;border-radius:12px;padding:16px 20px;margin:22px 0 6px}
.toc b{display:block;font-size:13px;color:var(--sub);letter-spacing:.04em;margin-bottom:8px}
.toc a{display:inline-block;margin:3px 14px 3px 0;font-size:14px;color:var(--pri);
 text-decoration:none;border-bottom:1px solid transparent}
.toc a:hover{border-bottom-color:var(--pri)}
@media print{body{background:#fff}.card{box-shadow:none;border:none;padding:0}.toc{break-inside:avoid}}
"""


def inline(t):
    t = H.escape(t)
    t = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', t)
    t = re.sub(r'`([^`]+)`', r'<code>\1</code>', t)
    return t


def slug(s, i):
    return 's%d' % i


def convert(md):
    lines = md.split('\n')
    out, toc = [], []
    i = 0
    h2i = 0
    in_ul = in_ol = False

    def close_lists():
        nonlocal in_ul, in_ol
        if in_ul:
            out.append('</ul>')
            in_ul = False
        if in_ol:
            out.append('</ol>')
            in_ol = False

    while i < len(lines):
        ln = lines[i].rstrip()
        s = ln.strip()

        if not s:
            close_lists()
            i += 1
            continue

        if s == '---':
            close_lists()
            out.append('<hr>')
            i += 1
            continue

        m = re.match(r'^(#{1,4})\s+(.*)$', s)
        if m:
            close_lists()
            lvl, txt = len(m.group(1)), m.group(2).strip()
            if lvl == 1:
                out.append('<div class="doc-title">%s</div>' % inline(txt))
            elif lvl == 2:
                h2i += 1
                aid = slug(txt, h2i)
                toc.append((aid, txt))
                out.append('<h2 id="%s">%s</h2>' % (aid, inline(txt)))
            else:
                out.append('<h3>%s</h3>' % inline(txt))
            i += 1
            continue

        if s.startswith('>'):
            close_lists()
            buf = []
            while i < len(lines) and lines[i].strip().startswith('>'):
                buf.append(lines[i].strip()[1:].strip())
                i += 1
            body = ''.join('<p>%s</p>' % inline(b) for b in buf if b)
            out.append('<blockquote>%s</blockquote>' % body)
            continue

        if re.match(r'^\d+[.、]\s+', s):
            if not in_ol:
                close_lists()
                out.append('<ol>')
                in_ol = True
            txt = re.sub(r'^\d+[.、]\s+', '', s)
            out.append('<li>%s</li>' % inline(txt))
            i += 1
            continue

        if s.startswith('- ') or s.startswith('* '):
            if not in_ul:
                close_lists()
                out.append('<ul>')
                in_ul = True
            out.append('<li>%s</li>' % inline(s[2:].strip()))
            i += 1
            continue

        close_lists()
        out.append('<p>%s</p>' % inline(s))
        i += 1

    close_lists()

    toc_html = ''
    if toc:
        toc_html = ('<div class="toc"><b>目录</b>' +
                    ''.join('<a href="#%s">%s</a>' % (a, inline(t)) for a, t in toc) + '</div>')
        # 插到第一个 h2 之前
        for k, seg in enumerate(out):
            if seg.startswith('<h2'):
                out.insert(k, toc_html)
                break

    body = '\n'.join(out)
    page = ('<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
            '<meta name="viewport" content="width=device-width,initial-scale=1">'
            '<title>诊断原料竞品市场情报</title><style>%s</style></head><body>'
            '<div class="wrap"><div class="card">%s</div></div></body></html>') % (CSS, body)
    return page


def main():
    if len(sys.argv) < 2:
        print('用法: python3 market_intel_html.py <md 路径>')
        sys.exit(1)
    src = os.path.abspath(sys.argv[1])
    md = open(src, encoding='utf-8').read()
    page = BK.inject(convert(md), theme='dark', tag='营销中心')
    dst = os.path.splitext(src)[0] + '.html'
    open(dst, 'w', encoding='utf-8').write(page)
    print('✅ 已生成:', dst, os.path.getsize(dst), 'bytes')
    return dst


if __name__ == '__main__':
    main()
