#!/usr/bin/env python3
# -*- coding: utf-8 -*-

r"""
将实验报告 Markdown（本仓库用法子集）转换为可编译的 LaTeX 内容文件（不含导言区）。

支持要点：
- 标题：#..###### → section/subsection/subsubsection/paragraph
- 行内代码：`...` → \codeinline{...}
- 加粗：**...** → \textbf{...}
- 代码块：```lang ... ``` → CodeBlock 环境（依赖 fvextra）
- 图片：![](path) → figure + includegraphics（无 caption，保持内容最小改动）
- 表格：GitHub 风格 pipe 表格 → tabularx + booktabs
- 列表：无序/有序列表 → itemize/enumerate（默认尽量保留原结构）
"""

from __future__ import annotations

import argparse
import re
from dataclasses import dataclass
import os
from pathlib import Path
from typing import Iterable


_HEADING_RE = re.compile(r"^(?P<hashes>#{1,6})\s+(?P<title>.+?)\s*$")
_FENCE_START_RE = re.compile(r"^```(?P<lang>[a-zA-Z0-9_-]+)?\s*$")
_FENCE_END_RE = re.compile(r"^```\s*$")
_IMAGE_RE = re.compile(r"!\[\s*]\((?P<path>[^)]+)\)\s*$")
_ORDERED_ITEM_RE = re.compile(r"^(?P<indent>\s*)(?P<num>\d+)[\.\)]\s+(?P<text>.+?)\s*$")
_BULLET_ITEM_RE = re.compile(r"^(?P<indent>\s*)[-*]\s+(?P<text>.+?)\s*$")
_HR_RE = re.compile(r"^\s*---\s*$")

_CODEBLOCK_SANITIZE = {
    "≤": "<=",
    "≥": ">=",
    "→": "->",
    "⇒": "=>",
}

_CJK_CHAR_RE = re.compile(r"[\u4e00-\u9fff]")


def _sanitize_code_text(raw: str) -> str:
    out = raw
    for k, v in _CODEBLOCK_SANITIZE.items():
        out = out.replace(k, v)
    return out


def _normalize_indent(raw: str) -> int:
    # 以 4 空格作为一个缩进层级的粗略估计（本仓库报告足够）。
    return len(raw.replace("\t", "    "))


def _escape_latex_outside_math(text: str) -> str:
    # 注意：这里不转义反斜杠，避免破坏已有 LaTeX 片段（如 \ge）。
    # 只在“非数学模式”中处理常见特殊字符。
    mapping = {
        "&": r"\&",
        "%": r"\%",
        "#": r"\#",
        "_": r"\_",
        "~": r"\textasciitilde{}",
        "^": r"\textasciicircum{}",
        "≤": r"$\leq$",
        "≥": r"$\geq$",
        "→": r"$\rightarrow$",
        "⇒": r"$\Rightarrow$",
        "④": "4",
    }

    out: list[str] = []
    i = 0
    in_math = False

    while i < len(text):
        ch = text[i]

        if ch == "$":
            # 兼容 $$...$$
            if i + 1 < len(text) and text[i + 1] == "$":
                out.append("$$")
                i += 2
                in_math = not in_math
                continue
            out.append("$")
            i += 1
            in_math = not in_math
            continue

        if not in_math and ch in mapping:
            out.append(mapping[ch])
        else:
            out.append(ch)
        i += 1

    return "".join(out)


def _convert_inline(markdown: str) -> str:
    # 先抽出行内代码，避免其中字符被转义。
    code_placeholders: list[str] = []

    def _code_repl(match: re.Match[str]) -> str:
        raw = _sanitize_code_text(match.group(1))
        placeholder = f"@@CODE{len(code_placeholders)}@@"
        if _CJK_CHAR_RE.search(raw):
            code_placeholders.append(rf"\texttt{{\detokenize{{{raw}}}}}")
        else:
            code_placeholders.append(rf"\codeinline{{{raw}}}")
        return placeholder

    # 行内代码
    text = re.sub(r"`([^`]+)`", _code_repl, markdown)

    # 加粗（最小实现：不处理跨行/嵌套）
    text = re.sub(r"\*\*(.+?)\*\*", r"\\textbf{\1}", text)

    # 转义特殊字符（数学模式外）
    text = _escape_latex_outside_math(text)

    # 恢复行内代码（其内部交给 \detokenize 处理）
    for idx, latex in enumerate(code_placeholders):
        text = text.replace(f"@@CODE{idx}@@", latex)

    return text


def _split_table_row(line: str) -> list[str]:
    # 去掉首尾 |，再按 | 切分
    raw = line.strip()
    if raw.startswith("|"):
        raw = raw[1:]
    if raw.endswith("|"):
        raw = raw[:-1]
    return [cell.strip() for cell in raw.split("|")]


def _is_table_separator(line: str) -> bool:
    # 典型：| --- | :---: | ---: |
    stripped = line.strip()
    if not stripped.startswith("|"):
        return False
    cells = _split_table_row(stripped)
    if not cells:
        return False
    for cell in cells:
        cell = cell.strip()
        if not cell:
            return False
        if not re.fullmatch(r":?-{3,}:?", cell):
            return False
    return True


@dataclass(frozen=True)
class _ListFrame:
    kind: str  # "itemize" | "enumerate"
    indent: int


def _close_lists(stack: list[_ListFrame], out: list[str]) -> None:
    while stack:
        frame = stack.pop()
        out.append(rf"\end{{{frame.kind}}}")


def _rewrite_resource_path(raw_path: str, source_file: Path, repo_root: Path) -> str:
    raw_path = raw_path.strip()
    if not raw_path:
        return raw_path

    if "://" in raw_path:
        return raw_path

    path = Path(raw_path)
    if path.is_absolute():
        return raw_path

    abs_path = (source_file.parent / path).resolve(strict=False)
    repo_root = repo_root.resolve(strict=False)
    try:
        rel_path = os.path.relpath(abs_path, repo_root)
    except ValueError:
        return raw_path

    return Path(rel_path).as_posix()


def convert_markdown_lines(lines: Iterable[str], *, source_file: Path, repo_root: Path) -> list[str]:
    out: list[str] = []
    list_stack: list[_ListFrame] = []

    in_code_block = False
    code_lines: list[str] = []

    pending_line_break = False

    lines = list(lines)
    i = 0

    while i < len(lines):
        raw_line = lines[i].rstrip("\n")

        if in_code_block:
            if _FENCE_END_RE.match(raw_line):
                _close_lists(list_stack, out)
                out.append(r"\begin{CodeBlock}")
                out.extend(code_lines)
                out.append(r"\end{CodeBlock}")
                out.append("")
                in_code_block = False
                code_lines = []
                i += 1
                continue

            sanitized = raw_line
            for k, v in _CODEBLOCK_SANITIZE.items():
                sanitized = sanitized.replace(k, v)
            code_lines.append(sanitized)
            i += 1
            continue

        # 代码块开始
        if _FENCE_START_RE.match(raw_line):
            _close_lists(list_stack, out)
            in_code_block = True
            code_lines = []
            i += 1
            continue

        # 水平分隔线
        if _HR_RE.match(raw_line):
            _close_lists(list_stack, out)
            out.append(r"\par\noindent\rule{\textwidth}{0.4pt}\par")
            out.append("")
            i += 1
            continue

        # 标题
        heading = _HEADING_RE.match(raw_line)
        if heading:
            _close_lists(list_stack, out)
            title = _convert_inline(heading.group("title"))
            level = len(heading.group("hashes"))
            if level <= 2:
                out.append(rf"\section{{{title}}}")
            elif level == 3:
                out.append(rf"\section{{{title}}}")
            elif level == 4:
                out.append(rf"\subsection{{{title}}}")
            elif level == 5:
                out.append(rf"\subsubsection{{{title}}}")
            else:
                out.append(rf"\paragraph{{{title}}}")
            out.append("")
            i += 1
            continue

        # 图片（单行）
        image = _IMAGE_RE.match(raw_line)
        if image:
            _close_lists(list_stack, out)
            path = _rewrite_resource_path(
                image.group("path"),
                source_file=source_file,
                repo_root=repo_root,
            )
            out.append(r"\begin{figure}[htbp]")
            out.append(r"    \centering")
            out.append(rf"    \includegraphics[width=0.92\textwidth]{{{path}}}")
            out.append(r"\end{figure}")
            out.append("")
            i += 1
            continue

        # 表格
        if raw_line.strip().startswith("|") and i + 1 < len(lines) and _is_table_separator(
            lines[i + 1].rstrip("\n")
        ):
            _close_lists(list_stack, out)
            header_cells = _split_table_row(raw_line)
            i += 2  # 跳过 separator 行

            body_rows: list[list[str]] = []
            while i < len(lines):
                row_line = lines[i].rstrip("\n")
                if not row_line.strip().startswith("|"):
                    break
                body_rows.append(_split_table_row(row_line))
                i += 1

            col_count = len(header_cells)
            colspec = " ".join([r">{\raggedright\arraybackslash}X"] * col_count)

            out.append(r"\begin{table}[htbp]")
            out.append(r"    \centering")
            out.append(rf"    \begin{{tabularx}}{{\textwidth}}{{{colspec}}}")
            out.append(r"        \toprule")
            header = " & ".join([rf"\textbf{{{_convert_inline(c)}}}" for c in header_cells])
            out.append(rf"        {header} \\")
            out.append(r"        \midrule")
            for row in body_rows:
                # 容错：行列数不齐时补空
                row = (row + [""] * col_count)[:col_count]
                cells = " & ".join([_convert_inline(c) for c in row])
                out.append(rf"        {cells} \\")
            out.append(r"        \bottomrule")
            out.append(r"    \end{tabularx}")
            out.append(r"\end{table}")
            out.append("")
            continue

        # 空行：结束列表，保留段落分隔
        if raw_line.strip() == "":
            _close_lists(list_stack, out)
            out.append("")
            i += 1
            continue

        # 列表项（有序/无序）
        ordered = _ORDERED_ITEM_RE.match(raw_line)
        bullet = _BULLET_ITEM_RE.match(raw_line)

        if ordered or bullet:
            match = ordered or bullet
            assert match is not None
            kind = "enumerate" if ordered else "itemize"
            indent = _normalize_indent(match.group("indent"))
            text = _convert_inline(match.group("text"))

            while list_stack and indent < list_stack[-1].indent:
                out.append(rf"\end{{{list_stack.pop().kind}}}")

            if not list_stack or indent > list_stack[-1].indent or kind != list_stack[-1].kind:
                if list_stack and indent == list_stack[-1].indent and kind != list_stack[-1].kind:
                    out.append(rf"\end{{{list_stack.pop().kind}}}")
                out.append(rf"\begin{{{kind}}}")
                list_stack.append(_ListFrame(kind=kind, indent=indent))

            out.append(rf"    \item {text}")
            i += 1
            continue

        # 普通文本（列表外）：做行内转换
        _close_lists(list_stack, out)
        line = raw_line
        if line.endswith("  "):
            pending_line_break = True
            line = line[:-2]
        converted = _convert_inline(line)
        if pending_line_break:
            converted += r"\\"
            pending_line_break = False
        out.append(converted)
        i += 1

    if in_code_block:
        # 容错：未闭合 fence
        _close_lists(list_stack, out)
        out.append(r"\begin{CodeBlock}")
        out.extend(code_lines)
        out.append(r"\end{CodeBlock}")
        out.append("")
    else:
        _close_lists(list_stack, out)

    return out


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--repo-root", type=Path, default=Path("."))
    args = parser.parse_args()

    md_text = args.input.read_text(encoding="utf-8")
    tex_lines = convert_markdown_lines(
        md_text.splitlines(),
        source_file=args.input,
        repo_root=args.repo_root,
    )
    args.output.write_text("\n".join(tex_lines).rstrip() + "\n", encoding="utf-8")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
