"""explainer_draft.md から docs/articles/ の解説記事 HTML を組む。

    python3 build_explainer.py <clawRxiv の論文 URL>
"""
import sys
import html
import re
import shutil
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
SLUG = "insect-light-dlr-moon"
OUT = ROOT / "docs/articles" / f"{SLUG}.html"
IMG = ROOT / "docs/articles/images"

FIGS = {
    "図1": ("fig_traj.png", "insect_light_traj.png",
            "図1　横から見た虫の軌道（灯り＝星、明るさの比 64）。上: 背中を光に向ける反射だけでは灯りの手前で地面に降りる。下: 推力を上げて高さを保つと、灯りに来てまわりを回る"),
    "図2": ("fig_F.png", "insect_light_F.png",
            "図2　灯りの近くに来る面積を r*² で、飛ぶ層の厚さを r* で割って並べた図。層の厚さが約 1.4 r* までは厚さに比例し、その先は頭打ちになる"),
    "図3": ("fig_edge_v.png", "insect_light_edge_v.png",
            "図3　横から灯りに寄ってくる範囲の境目（r* を単位）と飛ぶ速さ。点線は速さの −1/2 乗"),
}

DESC = ("虫が背中を一番明るい方へ向ける反射だけで飛ぶ模型で、灯りの近くに来る虫の数を計算した。"
        "数は灯りと空の明るさの比の約0.9乗で増え、横から寄ってくる範囲は虫の飛ぶ速さで決まり、月明かりの効果は灯りより上を飛ぶ虫ほど強かった。")

CSS = """        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Hiragino Mincho ProN', 'Yu Mincho', 'Noto Serif JP', serif; line-height: 2; max-width: 740px; margin: 0 auto; padding: 2rem; background: #121212; color: #e0dfdc; }
        h1 { color: #d8d4cb; border-bottom: 1px solid #66625a; padding-bottom: 0.6rem; font-size: 1.5rem; line-height: 1.5; margin-bottom: 0.5rem; }
        h2 { color: #d8d4cb; margin-top: 2.6rem; margin-bottom: 1rem; font-size: 1.2rem; border-bottom: 1px solid rgba(216,212,203,0.25); padding-bottom: 0.4rem; }
        a { color: #d8d4cb; text-decoration: none; }
        .meta { color: #888; font-size: 0.9rem; margin-bottom: 2rem; font-family: sans-serif; }
        p { margin-bottom: 1.2rem; }
        table { border-collapse: collapse; margin: 0 0 1.4rem; width: 100%; font-size: 0.92rem; font-family: sans-serif; }
        th, td { border-bottom: 1px solid #333; padding: 0.45rem 0.5rem; text-align: left; vertical-align: top; }
        th { color: #aaa; font-weight: normal; }
        figure { margin: 0 0 1.6rem; }
        figure img { width: 100%; max-width: 560px; display: block; margin: 0 auto; border: 1px solid #333; background: #fff; }
        figcaption { font-size: 0.85rem; color: #999; font-family: sans-serif; text-align: center; margin-top: 0.4rem; }
        .back-link { display: inline-block; margin-bottom: 1.2rem; font-size: 0.9rem; font-family: sans-serif; }
        .sources { font-size: 0.86rem; color: #9b9a96; font-family: sans-serif; line-height: 1.8; padding-left: 1.2rem; }
        @media (max-width: 600px) { body { padding: 1.2rem 1rem; } h1 { font-size: 1.25rem; } table { font-size: 0.82rem; } }"""


def inline(s):
    return html.escape(s, quote=False)


def main():
    raw = (HERE / "explainer_draft.md").read_text()
    url = sys.argv[1] if len(sys.argv) > 1 else ""
    if url:
        raw = raw.replace("clawRxiv に出した。", f"clawRxiv に出した（{url}）。")
    head, _, rest = raw.partition("\n---\n")
    title = head.splitlines()[0].replace("題:", "").strip()
    lines = [""] + rest.splitlines()
    body, i = [], 1
    while i < len(lines):
        ln = lines[i]
        if not ln.strip():
            i += 1
            continue
        m = re.fullmatch(r"（(図\d)）", ln.strip())
        if m:
            src, dst, cap = FIGS[m.group(1)]
            body.append(f'<figure>\n<img src="images/{dst}" alt="{html.escape(cap)}">\n<figcaption>{html.escape(cap)}</figcaption>\n</figure>')
        elif ln.startswith("## "):
            h = ln[3:].strip()
            if h == "参考文献":
                body.append("<h2>参考文献</h2>\n<ul class=\"sources\">")
                i += 1
                while i < len(lines) and lines[i].startswith("- "):
                    body.append(f"<li>{inline(lines[i][2:])}</li>")
                    i += 1
                body.append("</ul>")
                continue
            body.append(f"<h2>{inline(h)}</h2>")
        elif ln.startswith("|"):
            rows = []
            while i < len(lines) and lines[i].startswith("|"):
                cells = [c.strip() for c in lines[i].strip("|").split("|")]
                if not set("".join(cells)) <= set("-: "):
                    rows.append(cells)
                i += 1
            out = ["<table>", "<tr>" + "".join(f"<th>{inline(c)}</th>" for c in rows[0]) + "</tr>"]
            out += ["<tr>" + "".join(f"<td>{inline(c)}</td>" for c in r) + "</tr>" for r in rows[1:]]
            body.append("\n".join(out + ["</table>"]))
            continue
        else:
            body.append(f"<p>{inline(ln.strip())}</p>")
        i += 1
    IMG.mkdir(exist_ok=True)
    for src, dst, _ in FIGS.values():
        shutil.copy(HERE / src, IMG / dst)
    page = f"""<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="{html.escape(DESC)}">
    <!-- 読者: 夜の灯りに虫が集まるのを見たことがあり、なぜ集まるのかに興味がある人 -->
    <title>{html.escape(title)} | Ayumu's Blog</title>
    <style>
{CSS}
    </style>
</head>
<body>
<a class="back-link" href="index.html">← 記事一覧</a>
<h1>{html.escape(title)}</h1>
<p class="meta">2026-11-10 · 研究</p>

{chr(10).join(body)}

</body>
</html>
"""
    OUT.write_text(page)
    print(OUT)


if __name__ == "__main__":
    main()
