#!/usr/bin/env python3
"""从 OGRE 四卷的 Markdown 提取 L1 C++ 实验。"""

import argparse
from pathlib import Path
import re
from urllib.request import urlopen

VOLUMES = ('core', 'render', 'scene', 'ext')
ARTICLE = r'ogre-{volume}-\d{{2}}-[1-3]-[a-z0-9-]+'
EXAMPLE = re.compile(
    r'^\x60{3}cpp\n(// file: (src/[a-z0-9-]+\.cpp)\n// tier: L1\n.*?)^\x60{3}[ \t]*$',
    re.MULTILINE | re.DOTALL,
)
SITE = 'https://plumephp.com'


def fetch(url):
    with urlopen(url, timeout=30) as response:
        return response.read().decode('utf-8')


def collect(volume, source, site, origin):
    article = ARTICLE.format(volume=volume)
    if source:
        paths = sorted(source.glob(f'*/ogre-{volume}-*.md'))
        chapters = {p.stem: p.read_text(encoding='utf-8') for p in paths
                    if re.fullmatch(article, p.stem)}
    else:
        def read(slug):
            relative = f'{slug}/index.md'
            if site:
                return (site / relative).read_text(encoding='utf-8')
            return fetch(f'{origin}/{relative}')

        slugs = sorted(set(re.findall(article, read(f'ogre-{volume}-toc'))))
        if len(slugs) != 45:
            raise ValueError(f'{volume} 目录应有 45 节，得到 {len(slugs)}')
        chapters = {slug: read(slug) for slug in slugs}

    expected = {(ch, sec) for ch in range(1, 16) for sec in range(1, 4)}
    numbers = {tuple(map(int, slug.split('-')[2:4])) for slug in chapters}
    if len(chapters) != 45 or numbers != expected:
        raise ValueError(f'{volume} 正文章节不齐或编号重复')

    examples = {}
    for slug, markdown in chapters.items():
        matches = EXAMPLE.findall(markdown)
        if len(matches) != 1:
            raise ValueError(f'{slug} 应有且仅有一个 L1 C++ 实验')
        code, filename = matches[0]
        if filename in examples:
            raise ValueError(f'{volume} 重复的实验文件 {filename}')
        examples[filename] = code
    return examples


RUN = '''#!/bin/sh
set -eu
cd "$(dirname "$0")"
mkdir -p bin
for source in src/*.cpp; do
    name=$(basename "$source" .cpp)
    "${CXX:-clang++}" -std=c++20 -Wall -I. "$source" -o "bin/$name"
    "./bin/$name"
done
'''


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    location = parser.add_mutually_exclusive_group()
    location.add_argument('--source', type=Path, help='仓库的 content/posts/books 目录')
    location.add_argument('--site', type=Path, help='已生成的 Hugo 站点目录')
    location.add_argument('--origin', default=SITE, help='含 Markdown 输出的站点 URL')
    parser.add_argument('--volume', choices=VOLUMES, action='append')
    parser.add_argument('--output', type=Path, required=True, help='新的输出目录')
    args = parser.parse_args()

    if args.output.exists():
        parser.error('--output 必须指向一个新的目录')
    header = Path(__file__).with_name('verify.h').read_text(encoding='utf-8')
    volumes = args.volume or VOLUMES
    if len(set(volumes)) != len(volumes):
        parser.error('--volume 不能重复指定同一卷')
    collected = {
        volume: collect(volume, args.source, args.site, args.origin.rstrip('/'))
        for volume in volumes
    }
    args.output.mkdir(parents=True)
    for volume, examples in collected.items():
        project = args.output / f'ogre-{volume}-lab'
        (project / 'src').mkdir(parents=True)
        (project / 'verify.h').write_text(header, encoding='utf-8')
        (project / 'run_all.sh').write_text(RUN, encoding='utf-8')
        for filename, code in examples.items():
            (project / filename).write_text(code, encoding='utf-8')
        print(f'{project}: {len(examples)} 个实验')


if __name__ == '__main__':
    main()
