"""Render the prediction collection for xpeg's existing static document root."""

import html
import json
import os
from pathlib import Path
import re
import subprocess
from urllib.parse import quote, unquote, urlsplit, urlunsplit


COLLECTION = Path(__file__).resolve().parents[1] / "jg-prediction"
PRACTICE = "2027年度 予想問題"
DOCUMENTS = {
    f"{PRACTICE}/問題.md": "予想模試 理科・社会 第1回・第2回",
    f"{PRACTICE}/解答・解説.md": "予想模試 解答・解説",
    "2027年度_女子学院_理科_予想問題集.md": "理科 予想問題集",
    "2027年度_女子学院_社会_予想問題集.md": "社会 予想問題集",
    "astra-女子学院2027年度 出題予想/理科.md": "Astra 理科",
    "astra-女子学院2027年度 出題予想/社会.md": "Astra 社会",
    "fable-女子学院 理科 出題分析と2027年度予想.md": "Fable 理科",
    "fable-女子学院 社会 出題分析と2027年度予想.md": "Fable 社会",
    "neon-jg_2027_science_prediction_report.md": "Neon 理科",
    "neon-jg_2027_social_prediction_report.md": "Neon 社会",
}

TEMPLATE = """<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>$pagetitle$</title>
<link rel="stylesheet" href="$stylesheet$">
</head>
<body>
<header class="site-header"><div class="frame">
  <a href="$home$">女子学院 2027年度対策</a>
  $if(source)$<a class="source" href="$source$">Markdown原稿</a>$endif$
</div></header>
<main class="frame reading">
$if(toc)$
<details class="toc" open>
  <summary>目次</summary>
  <nav aria-label="目次">$table-of-contents$</nav>
</details>
$endif$
<article>$body$</article>
</main>
</body>
</html>
"""


def run(command, data=None):
    return subprocess.run(command, input=data, text=True, capture_output=True, check=True).stdout


def nodes(value):
    if isinstance(value, dict):
        yield value
        if "c" in value:
            yield from nodes(value["c"])
    elif isinstance(value, list):
        for item in value:
            yield from nodes(item)


def rewrite_target(target, source):
    url = urlsplit(target)
    if url.scheme or url.netloc or not url.path or url.path.startswith("/"):
        return target
    path = (source.parent / unquote(url.path)).resolve()
    if not path.is_file() and path.parent.name == "過去問":
        candidate = COLLECTION.parent / "過去問" / path.name
        if candidate.is_file():
            path = candidate
    if path.suffix.lower() == ".md" and path.is_relative_to(COLLECTION) and path.is_file():
        path = path.with_suffix(".html")
    link = quote(os.path.relpath(path, source.parent))
    return urlunsplit(("", "", link, url.query, url.fragment))


def draw_flowchart(source, diagram):
    """Render the simple labeled flowcharts used in the Neon reports."""
    labels = {}
    edges = []
    for line in diagram.splitlines()[1:]:
        ends = []
        for part in line.split("-->"):
            match = re.fullmatch(r'\s*(\w+)(?:[\[{]"([^"]+)"[\]}])?\s*', part)
            if not match:
                raise ValueError(f"Unsupported Mermaid element in {source.name}: {part}")
            name, label = match.groups()
            if label:
                labels[name] = label
            ends.append(name)
        edges.append(f"{ends[0]} -> {ends[1]};")

    def label_lines(label, width=16):
        return "\n".join(label[start:start + width] for start in range(0, len(label), width))

    declarations = [
        f"{name} [label={json.dumps(label_lines(label), ensure_ascii=False)}];"
        for name, label in labels.items()
    ]
    graph = """
    digraph {
      graph [rankdir=LR, bgcolor="transparent", pad=.12, nodesep=.15, ranksep=.32];
      node [shape=box, style="rounded,filled", color="#78a39a", fillcolor="#f1f7f5",
            fontname="Noto Sans CJK JP", fontsize=13, margin=".12,.08"];
      edge [color="#658880", arrowsize=.65];
    """
    svg = run(["dot", "-Tsvg"], graph + "\n".join(declarations + edges) + "}")
    description = "。".join(f"{labels[a]} → {labels[b]}" for a, b in (
        re.findall(r"\w+", edge) for edge in edges
    ))
    drawing = svg[svg.index("<svg"):]
    drawing = drawing.replace("<svg ", '<svg aria-hidden="true" ', 1)
    return f'<div class="diagram" role="img" aria-label="{html.escape(description)}">{drawing}</div>'


def render_report(source, template):
    document = json.loads(run(["pandoc", "-f", "markdown+alerts", "-t", "json", str(source)]))
    for node in nodes(document["blocks"]):
        if node["t"] in {"Link", "Image"}:
            target = node["c"][2]
            target[0] = rewrite_target(target[0], source)
        elif node["t"] == "CodeBlock" and "mermaid" in node["c"][0][1]:
            node["t"] = "RawBlock"
            node["c"] = ["html", draw_flowchart(source, node["c"][1])]
        elif node["t"] in {"RawInline", "RawBlock"} and node["c"][0] == "html":
            # The Markdown sources use line breaks within table cells.
            if not re.fullmatch(r"\s*<br\s*/?>\s*", node["c"][1], re.IGNORECASE):
                node["t"], node["c"] = "Str" if node["t"] == "RawInline" else "Plain", "" if node["t"] == "RawInline" else []

    prefix = "../" * len(source.relative_to(COLLECTION).parent.parts)
    title = DOCUMENTS[source.relative_to(COLLECTION).as_posix()]
    page = run(
        [
            "pandoc", "-f", "json", "-t", "html5", "--standalone", "--mathml",
            "--toc", "--toc-depth=2", "--section-divs", "--template", str(template),
            "-V", f"pagetitle={title}｜女子学院 2027年度対策",
            "-V", f"home={prefix}index.html",
            "-V", f"stylesheet={prefix}reading.css",
            "-V", f"source={quote(source.name)}",
        ],
        json.dumps(document, ensure_ascii=False),
    )
    source.with_suffix(".html").write_text(page, encoding="utf-8")


def link(path, label):
    relative = Path(path)
    if relative.suffix == ".md":
        relative = relative.with_suffix(".html")
    return f'<a href="{quote(relative.as_posix())}">{html.escape(label)}</a>'


def render_index():
    documents = list(DOCUMENTS)
    exam_rows = "\n".join(
        f"<tr><th scope=\"row\">{subject}</th>"
        + "".join(f"<td>{link(f'{PRACTICE}/{subject} 第{i}回 問題.pdf', f'第{i}回 PDF')}</td>" for i in (1, 2))
        + "</tr>"
        for subject in ("理科", "社会")
    )
    report_rows = "\n".join(
        f'<tr><th scope="row">{model}</th>'
        f'<td>{link(documents[i], "理科の予想")}</td>'
        f'<td>{link(documents[i + 1], "社会の予想")}</td></tr>'
        for i, model in zip((4, 6, 8), ("Astra", "Fable", "Neon"))
    )
    index = f"""<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>女子学院 2027年度対策</title>
<link rel="stylesheet" href="reading.css">
</head>
<body>
<main class="frame index">
<h1>女子学院 2027年度対策</h1>
<p class="intro">理科・社会の予想模試、問題集、AIの出題分析。</p>
<section>
  <h2>予想模試</h2>
  <p>理科・社会 各2回／各40分</p>
  <ul class="actions">
    <li>{link(documents[0], "問題を読む")}</li>
    <li>{link(documents[1], "解答・解説を読む")}</li>
  </ul>
  <h3>印刷用PDF</h3>
  <table><tbody>{exam_rows}</tbody></table>
  <p>{link(f"{PRACTICE}/解答・解説.pdf", "全4回の解答・解説 PDF")}</p>
</section>
<section>
  <h2>追加の予想問題集</h2>
  <ul class="actions">
    <li>{link(documents[2], "理科の問題集")}</li>
    <li>{link(documents[3], "社会の問題集")}</li>
  </ul>
</section>
<section>
  <h2>AIの出題分析と予想</h2>
  <table><tbody>{report_rows}</tbody></table>
</section>
</main>
</body>
</html>
"""
    (COLLECTION / "index.html").write_text(index, encoding="utf-8")


if __name__ == "__main__":
    from tempfile import TemporaryDirectory

    with TemporaryDirectory(prefix="jg-prediction-") as tmp:
        template = Path(tmp) / "reading.html"
        template.write_text(TEMPLATE, encoding="utf-8")
        for relative in DOCUMENTS:
            render_report(COLLECTION / relative, template)
    render_index()
