#!/usr/bin/env python3
"""为资源包生成 manifest.json（SHA-256）。禁止扫到学习记录。

默认扫描 html/estudy 下已落地的 ASCII 树。全量拷贝前可用 --root 指向样本目录。

  python tasks/data-platform/migration/03-hash-manifest.py --root E:/nginx-1.8.0/html/estudy --dry-run
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys
from datetime import datetime, timezone
from pathlib import Path

FORBIDDEN_PARTS = {
    "learning",
    "reading-records",
    "reports",
    "srs.json",
    "profile.json",
    "days.json",
}


def sha256_file(path: Path, buf: int = 1024 * 1024) -> str:
    h = hashlib.sha256()
    with path.open("rb") as fh:
        while True:
            chunk = fh.read(buf)
            if not chunk:
                break
            h.update(chunk)
    return h.hexdigest()


def rel_posix(path: Path, root: Path) -> str:
    return path.relative_to(root).as_posix()


def assert_l1_only(path: Path) -> None:
    parts = {p.lower() for p in path.parts}
    names = {path.name.lower()}
    hit = (parts | names) & {x.lower() for x in FORBIDDEN_PARTS}
    if hit:
        raise SystemExit(f"refusing to pack user data: {path} hit {sorted(hit)}")


def iter_files(folder: Path):
    if not folder.exists():
        return
    for p in folder.rglob("*"):
        if p.is_file() and p.name != "manifest.json":
            yield p


def pack_checksum(items: list[dict]) -> str:
    h = hashlib.sha256()
    for it in sorted(items, key=lambda x: x["path"]):
        line = f"{it['path']}\0{it['bytes']}\0{it['sha256']}\n".encode("utf-8")
        h.update(line)
    return h.hexdigest()


def build_pack(pack_id: str, kind: str, version: str, files_root: Path, file_paths: list[Path]) -> dict:
    items = []
    for p in file_paths:
        assert_l1_only(p)
        items.append(
            {
                "path": rel_posix(p, files_root),
                "bytes": p.stat().st_size,
                "sha256": sha256_file(p),
            }
        )
    items.sort(key=lambda x: x["path"])
    return {
        "id": pack_id,
        "kind": kind,
        "version": version,
        "checksum": pack_checksum(items),
        "checksum_alg": "sha256-of-sorted-path-bytes-sha256",
        "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "items": items,
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, required=True, help="html/estudy 根")
    parser.add_argument("--mapping", type=Path, default=Path(__file__).with_name("mapping") / "books.csv")
    parser.add_argument("--book-id", default="", help="只打一本，如 stage-03__AtTheSeaside")
    parser.add_argument("--version", default="1")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--write", action="store_true", help="把 manifest 写到 manifests/ 与包目录")
    args = parser.parse_args()
    root: Path = args.root
    if not root.is_dir():
        print(f"missing root {root}", file=sys.stderr)
        return 1

    # 课程核心包：tts / phonemes / catalog / 闪卡（不含 learning）
    # 与 03 正文 core-runtime 对齐；SPA 在未部署到 html/estudy 时跳过。
    core_dirs = [
        root / "audio" / "tts-words",
        root / "audio" / "phonemes",
        root / "audio" / "en",
        root / "audio" / "cn",
        root / "data",
        root / "courses" / "opw-flashcards",
    ]
    core_files: list[Path] = []
    for d in core_dirs:
        core_files.extend(iter_files(d))
    if core_files:
        core = build_pack("core-runtime", "core", args.version, root, core_files)
        print(f"core-runtime files={len(core['items'])} checksum={core['checksum'][:12]}...")
        if args.write and not args.dry_run:
            out = root / "manifests" / "core-runtime.json"
            out.parent.mkdir(parents=True, exist_ok=True)
            out.write_text(json.dumps(core, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

    if not args.mapping.is_file():
        print("no books.csv, skip per-book manifests")
        return 0

    import csv

    seen: set[str] = set()
    with args.mapping.open(encoding="utf-8-sig") as fh:
        for row in csv.DictReader(fh):
            bid = row["book_id"]
            if args.book_id and bid != args.book_id:
                continue
            if bid in seen:
                continue
            seen.add(bid)
            stage = row["stage"]
            slug = row["fs_slug"]
            img = root / "images" / "books" / stage / slug
            audio = root / "audio" / "books" / stage / slug
            files = list(iter_files(img)) + list(iter_files(audio))
            catalog = root / "data" / "book-structured" / stage / f"{row['img_folder']}.json"
            if catalog.is_file():
                files.append(catalog)
            if not files:
                print(f"skip empty pack {bid}")
                continue
            pack = build_pack(f"book:{bid}", "book", args.version, root, files)
            print(f"{bid} files={len(pack['items'])} bytes={sum(i['bytes'] for i in pack['items'])} checksum={pack['checksum'][:12]}...")
            if args.write and not args.dry_run:
                # 文件名用 stage__fs_slug（ASCII）；JSON id 仍是 book:{逻辑 book_id}
                out = root / "manifests" / "book" / f"{stage}__{slug}.json"
                out.parent.mkdir(parents=True, exist_ok=True)
                out.write_text(json.dumps(pack, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
                if img.is_dir():
                    (img / "manifest.json").write_text(json.dumps(pack, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
