# -*- coding: utf-8 -*-
"""
将 v26/main_ai_discussion.md 转换为 main_ai_discussion.html（AI 讨论专用版）
设计要求：
- 与 v26 站点主题一致（深色标题区、阅读设置面板、主题切换）
- 简化结构（无侧边栏、无 TTS 面板）— 专为 AI 讨论场景
- 保持可读性（16:9 / 1280px 容器）
- 自动包含 main.js 以支持主题切换
"""
import re
import html
from pathlib import Path

ROOT = Path(r"E:\GitHub3\article\四把尺子理论\v26")
SOURCE_MD = ROOT / "main_ai_discussion.md"
TARGET_HTML = ROOT / "main_ai_discussion.html"


def load_markdown(path: Path) -> str:
    """读取 Markdown 文件。"""
    return path.read_text(encoding="utf-8")


def preprocess_markdown(md: str) -> str:
    """预处理：合并被翻译或拷贝导致的标题符号问题。"""
    import re as _re
    md = _re.sub(r'(^|\n)(#(?: +#+)+#?)', lambda m: f"{m.group(1)}{'#' * m.group(2).count('#')}", md)
    md = _re.sub(r'(^|\n)(#)(?:\s+#)+', lambda m: f"{m.group(1)}{'#' * m.group(2).count('#')}", md)
    for _ in range(5):
        new_md = _re.sub(r'\* \*', '*', md)
        if new_md == md:
            break
        md = new_md
    for _ in range(5):
        new_md = _re.sub(r'\*\* \*\*', '**', md)
        if new_md == md:
            break
        md = new_md
    return md


def escape_html(text: str) -> str:
    """转义 HTML 特殊字符。"""
    return html.escape(text, quote=True)


def format_inline(text: str) -> str:
    """处理行内 markdown 格式：加粗、代码、链接、斜体、图片。"""
    code_blocks = {}

    def save_code(match):
        key = f"\x00CODE{len(code_blocks)}\x00"
        code_blocks[key] = f"<code>{escape_html(match.group(1))}</code>"
        return key

    text = re.sub(r"`([^`\n]+)`", save_code, text)
    images = {}

    def save_image(match):
        key = f"\x00IMG{len(images)}\x00"
        alt = escape_html(match.group(1))
        src = match.group(2)
        images[key] = f'<img src="{escape_html(src)}" alt="{alt}" loading="lazy">'
        return key

    text = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", save_image, text)
    links = {}

    def save_link(match):
        key = f"\x00LINK{len(links)}\x00"
        text_part = match.group(1)
        url_part = match.group(2)
        links[key] = f'<a href="{escape_html(url_part)}">{escape_html(text_part)}</a>'
        return key

    text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", save_link, text)
    text = escape_html(text)
    text = re.sub(r"\*\*([^*\n]+)\*\*", r"<strong>\1</strong>", text)
    text = re.sub(r"(?<!\*)\*\s*([^*\n][^*\n]*?)\s*\*(?!\*)", r"<em>\1</em>", text)
    for k, v in images.items():
        text = text.replace(k, v)
    for k, v in links.items():
        text = text.replace(k, v)
    for k, v in code_blocks.items():
        text = text.replace(k, v)
    return text


def md_to_html(md: str) -> str:
    """Markdown → HTML 转换（支持 H1-H6 / 列表 / 引用 / 表格 / 段落）。"""
    md = preprocess_markdown(md)
    lines = md.splitlines()
    out = []
    in_code = False
    code_buf = []
    in_list = None
    list_buf = []
    in_table = False
    table_buf = []

    def flush_list():
        nonlocal list_buf, in_list
        if in_list and list_buf:
            tag = in_list
            out.append(f"<{tag}>")
            for item in list_buf:
                out.append(f"  <li>{format_inline(item)}</li>")
            out.append(f"</{tag}>")
        list_buf = []
        in_list = None

    def flush_table():
        nonlocal table_buf, in_table
        if not table_buf:
            in_table = False
            return
        sep_re = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$")
        if len(table_buf) >= 2 and sep_re.match(table_buf[1]):
            header_cells = [c.strip() for c in table_buf[0].strip().strip("|").split("|")]
            body_rows = table_buf[2:]
            out.append("<table>")
            out.append("<thead><tr>")
            for cell in header_cells:
                out.append(f"  <th>{format_inline(cell)}</th>")
            out.append("</tr></thead>")
            if body_rows:
                out.append("<tbody>")
                for row in body_rows:
                    cells = [c.strip() for c in row.strip().strip("|").split("|")]
                    out.append("<tr>")
                    for cell in cells:
                        out.append(f"  <td>{format_inline(cell)}</td>")
                    out.append("</tr>")
                out.append("</tbody>")
            out.append("</table>")
        else:
            for row in table_buf:
                out.append(f"<p>{format_inline(row)}</p>")
        table_buf = []
        in_table = False

    for raw in lines:
        line = raw.rstrip()
        if line.strip().startswith("```"):
            flush_list()
            flush_table()
            if in_code:
                out.append("<pre><code>" + "\n".join(code_buf) + "</code></pre>")
                code_buf = []
                in_code = False
            else:
                in_code = True
            continue
        if in_code:
            code_buf.append(line)
            continue

        stripped = line.strip()
        if not stripped:
            flush_list()
            flush_table()
            out.append("")
            continue
        # 标题：支持 H1-H6
        if stripped.startswith("######"):
            flush_list()
            flush_table()
            out.append(f"<h6>{format_inline(stripped[6:].strip())}</h6>")
            continue
        if stripped.startswith("#####"):
            flush_list()
            flush_table()
            out.append(f"<h5>{format_inline(stripped[5:].strip())}</h5>")
            continue
        if stripped.startswith("####"):
            flush_list()
            flush_table()
            out.append(f"<h4>{format_inline(stripped[4:].strip())}</h4>")
            continue
        if stripped.startswith("###"):
            flush_list()
            flush_table()
            out.append(f"<h3>{format_inline(stripped[3:].strip())}</h3>")
            continue
        if stripped.startswith("##"):
            flush_list()
            flush_table()
            out.append(f"<h2>{format_inline(stripped[2:].strip())}</h2>")
            continue
        if stripped.startswith("# "):
            flush_list()
            flush_table()
            out.append(f"<h1>{format_inline(stripped[2:].strip())}</h1>")
            continue
        if stripped == "---":
            flush_list()
            flush_table()
            out.append("<hr>")
            continue
        if stripped.startswith("> "):
            flush_list()
            flush_table()
            out.append(f"<blockquote><p>{format_inline(stripped[2:])}</p></blockquote>")
            continue
        # 表格
        if stripped.startswith("|") and stripped.endswith("|"):
            in_table = True
            table_buf.append(stripped)
            continue
        if in_table:
            flush_table()
        # 列表
        if stripped.startswith("- "):
            if in_list != "ul":
                flush_list()
                in_list = "ul"
            list_buf.append(stripped[2:])
            continue
        if re.match(r"^\d+\.\s", stripped):
            if in_list != "ol":
                flush_list()
                in_list = "ol"
            list_buf.append(re.sub(r"^\d+\.\s", "", stripped))
            continue
        # 段落
        flush_list()
        out.append(f"<p>{format_inline(stripped)}</p>")

    flush_list()
    flush_table()
    if in_code and code_buf:
        out.append("<pre><code>" + "\n".join(code_buf) + "</code></pre>")
    return "\n".join(out)


def build_html() -> str:
    """构建完整 HTML 页面。"""
    body = load_markdown(SOURCE_MD)
    content = md_to_html(body)
    # 提取主标题（第一行 H1）
    title = "四把尺子理论 v26 — AI 讨论专用版（v26.1.7）"
    # 统计字符数
    char_count = len(body)
    line_count = len(body.splitlines())
    # 渲染页面
    return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="Expires" content="0">
  <title>{title}</title>
  <link rel="stylesheet" href="css/entry-common.css">
  <link rel="stylesheet" href="main.css">
  <style>
    /* AI 讨论专用版样式 */
    body {{
      font-family: "PingFang SC", "Microsoft YaHei", "Helvetica Neue", sans-serif;
      line-height: 1.9;
      color: var(--text);
      background: var(--bg);
      min-height: 100vh;
      font-size: calc(16px * var(--font-scale, 1));
    }}
    .ai-discussion-container {{
      max-width: 1280px;
      margin: 0 auto;
      padding: 12px 20px 20px;
    }}
    .ai-header {{
      background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
      color: #ffffff;
      padding: 40px 50px;
      border-radius: 16px;
      margin-bottom: 24px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.15);
      border: 2px solid #6366f1;
    }}
    .ai-header h1 {{
      font-size: 2.1em;
      font-weight: 700;
      margin-bottom: 16px;
      letter-spacing: 1px;
    }}
    .ai-header .ai-badge {{
      display: inline-block;
      background: #6366f1;
      color: #fff;
      padding: 4px 14px;
      border-radius: 20px;
      font-size: 0.85em;
      font-weight: 600;
      margin-bottom: 12px;
      letter-spacing: 0.5px;
    }}
    .ai-header .meta {{
      font-size: 0.95em;
      opacity: 0.9;
      line-height: 1.9;
    }}
    .ai-header .meta p {{ margin: 4px 0; }}
    .ai-header .meta a {{ color: #93c5fd; text-decoration: none; }}
    .ai-header .meta a:hover {{ text-decoration: underline; }}
    .ai-content {{
      background: var(--panel-bg);
      padding: 36px 50px;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0,0,0,0.06);
      border: 1px solid var(--panel-border);
    }}
    .ai-content h1, .ai-content h2, .ai-content h3, .ai-content h4, .ai-content h5, .ai-content h6 {{
      color: var(--text);
      margin: 1.4em 0 0.6em 0;
      font-weight: 700;
      line-height: 1.4;
    }}
    .ai-content h1 {{ font-size: 1.9em; border-bottom: 3px solid var(--link); padding-bottom: 12px; }}
    .ai-content h2 {{
      font-size: 1.6em;
      border-left: 4px solid var(--link);
      padding-left: 14px;
      margin-top: 2em;
      color: #6366f1;
    }}
    .ai-content h3 {{ font-size: 1.3em; color: var(--text); }}
    .ai-content h4 {{ font-size: 1.1em; color: var(--muted); }}
    .ai-content h5 {{ font-size: 1.0em; color: var(--muted); font-style: italic; }}
    .ai-content h6 {{ font-size: 0.95em; color: var(--muted); }}
    .ai-content p {{ margin: 0.9em 0; color: var(--text); }}
    .ai-content strong {{ color: var(--link); font-weight: 700; }}
    .ai-content em {{ color: var(--link-hover, var(--link)); font-style: italic; }}
    .ai-content a {{ color: var(--link); text-decoration: none; border-bottom: 1px solid var(--link); }}
    .ai-content a:hover {{ color: var(--link-hover); border-bottom-color: var(--link-hover); }}
    .ai-content ul, .ai-content ol {{ margin: 0.8em 0 0.8em 1.5em; color: var(--text); }}
    .ai-content li {{ margin: 0.35em 0; }}
    .ai-content blockquote {{
      border-left: 4px solid #6366f1;
      background: var(--quote-bg);
      padding: 14px 20px;
      margin: 1.2em 0;
      border-radius: 0 8px 8px 0;
      color: var(--text);
    }}
    .ai-content blockquote p {{ color: var(--text); margin: 0.3em 0; }}
    .ai-content hr {{ border: none; border-top: 2px dashed var(--panel-border); margin: 2em 0; }}
    .ai-content code {{
      background: var(--pill-bg);
      padding: 2px 6px;
      border-radius: 4px;
      font-family: "Consolas", "Monaco", monospace;
      font-size: 0.92em;
      color: var(--link);
    }}
    .ai-content pre {{
      background: #1e293b;
      color: #e2e8f0;
      padding: 18px;
      border-radius: 8px;
      overflow-x: auto;
      margin: 1em 0;
    }}
    .ai-content pre code {{ background: none; color: inherit; padding: 0; }}
    .ai-content table {{
      width: 100%;
      border-collapse: separate;
      border-spacing: 0;
      margin: 1.4em 0;
      border-radius: 10px;
      overflow: hidden;
      box-shadow: 0 4px 18px rgba(31, 41, 55, 0.08);
      border: 1px solid var(--panel-border);
      font-size: 0.96em;
    }}
    .ai-content thead {{
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      color: #ffffff;
    }}
    .ai-content th, .ai-content td {{
      border: none;
      border-bottom: 1px solid var(--panel-border);
      border-right: 1px solid var(--panel-border);
      padding: 12px 16px;
      text-align: left;
      line-height: 1.6;
      color: var(--text);
    }}
    .ai-content th:last-child, .ai-content td:last-child {{ border-right: none; }}
    .ai-content tbody tr:last-child td {{ border-bottom: none; }}
    .ai-content th {{
      font-weight: 700;
      letter-spacing: 0.02em;
      color: #ffffff;
    }}
    .ai-content tbody tr {{ background: var(--panel-bg); transition: background-color 0.2s ease; }}
    .ai-content tbody tr:nth-child(even) {{ background: var(--bg); }}
    .ai-content tbody tr:hover {{ background: var(--quote-bg); }}
    .ai-content table code {{
      background: var(--pill-bg);
      color: var(--link);
      padding: 1px 6px;
      border-radius: 4px;
      font-size: 0.9em;
    }}
    .ai-nav {{
      margin-top: 30px;
      padding: 20px 28px;
      background: var(--quote-bg);
      border-left: 4px solid #6366f1;
      border-radius: 6px;
      font-size: 0.95em;
    }}
    .ai-nav a {{ color: var(--link); text-decoration: none; margin-right: 16px; }}
    .ai-nav a:hover {{ color: var(--link-hover); text-decoration: underline; }}
    .ai-footer-info {{
      margin-top: 30px;
      padding: 16px 24px;
      background: #1e293b;
      color: #e2e8f0;
      border-radius: 8px;
      font-size: 0.88em;
      line-height: 1.7;
    }}
    .ai-footer-info code {{
      background: #334155;
      color: #93c5fd;
      padding: 2px 8px;
      border-radius: 4px;
    }}
    @media (max-width: 768px) {{
      .ai-discussion-container {{ padding: 8px 12px 12px; }}
      .ai-header {{ padding: 30px 22px; }}
      .ai-header h1 {{ font-size: 1.6em; }}
      .ai-content {{ padding: 22px 18px; }}
      .ai-content h1 {{ font-size: 1.4em; }}
      .ai-content h2 {{ font-size: 1.3em; }}
      .ai-content table {{ font-size: 0.88em; display: block; overflow-x: auto; white-space: nowrap; }}
      .ai-content th, .ai-content td {{ padding: 9px 12px; }}
    }}
  </style>
</head>
<body>
  <aside class="font-zoom is-collapsed" id="font-zoom-panel" aria-label="阅读设置">
    <button type="button" class="font-zoom-toggle" data-font-zoom-toggle aria-label="打开阅读设置">
      <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <text x="12" y="16" text-anchor="middle" font-size="14" font-weight="700" fill="currentColor" stroke="none">Aa</text>
        <line x1="3" y1="20" x2="21" y2="20"/>
      </svg>
    </button>
    <div class="font-zoom-body">
      <div class="font-zoom-label">阅读设置</div>
      <button type="button" data-font-zoom="decrease">A-</button>
      <button type="button" data-font-zoom="reset">重置</button>
      <button type="button" data-font-zoom="increase">A+</button>
      <select data-theme-mode="select" aria-label="主题">
        <option value="auto">主题：自动</option>
        <option value="light">主题：浅色</option>
        <option value="dark">主题：深色</option>
        <option value="black">主题：黑色护眼</option>
        <option value="forest">主题：暗绿护眼</option>
        <option value="slate">主题：暗灰蓝护眼</option>
        <option value="purple">主题：暗紫护眼</option>
        <option value="sepia">主题：暖色护眼</option>
      </select>
    </div>
  </aside>
  <div class="ai-discussion-container">
    <header class="ai-header">
      <span class="ai-badge">🤖 AI 讨论专用版 v26.1.7</span>
      <h1>{title}</h1>
      <div class="meta">
        <p><strong>定位：</strong>v26 框架的"AI 可投喂"精简版 — 适用于发给 AI 讨论、复制到 path-finder、生成 PPT 提示词、跨理论项目做参考输入</p>
        <p><strong>源文件：</strong>本目录 <code>main_ai_discussion.md</code>（约 {char_count:,} 字符 / {line_count} 行）</p>
        <p><strong>精简原则：</strong>可推理想到的就不写 — 只保留 AI 不能自动推理出的核心原创洞见、关键论证、反直觉判断、原创金句与跨理论同步</p>
        <p><strong>主入口：</strong><a href="index.html">v26 索引</a> · <a href="main.html">主文整稿</a> · <a href="main_ai_discussion.md">查看 Markdown 母本</a> · <a href="popular.html">通俗版</a> · <a href="supplements/index.html">补充专题子站</a></p>
      </div>
    </header>
    <article class="ai-content">
{content}
    </article>
    <div class="ai-nav">
      <a href="index.html">v26 索引</a>
      <a href="main.html">主文整稿</a>
      <a href="popular.html">通俗版</a>
      <a href="supplements/index.html">补充专题子站</a>
      <a href="main_ai_discussion.md">查看 Markdown 母本</a>
    </div>
    <div class="ai-footer-info">
      💡 <strong>使用建议</strong>：与 AI 讨论时，<strong>直接复制本页面正文</strong>作为讨论背景；让 AI 找出本文"未明确说明"的部分、用本文核心命题检测新场景、或用金句识别现实事件核心矛盾。
      <br>⚠️ <strong>注意</strong>：本文已删除 AI 可推理的内容；<strong>不要让 AI 自动补全</strong>，否则会引入 AI 偏好而非 v26 洞见。
    </div>
  </div>
  <script src="main.js"></script>
  <script type="text/javascript" src="/common/js/baidu_tongji.js"></script>
</body>
</html>
"""


def main():
    """主函数：生成 HTML 文件。"""
    if not SOURCE_MD.exists():
        print(f"[error] 源文件不存在: {SOURCE_MD}")
        return
    html_content = build_html()
    TARGET_HTML.write_text(html_content, encoding="utf-8")
    size = TARGET_HTML.stat().st_size
    print(f"[ok]   {SOURCE_MD.name} -> {TARGET_HTML.name} ({size:,} 字节)")


if __name__ == "__main__":
    main()
