#!/usr/bin/env bash
# 按 mapping/books.csv 迁移到 $DEST/estudy（默认 dry-run）。
# 同卷用 ln（硬链接），跨卷 cp -a。不要在未核对 mapping 前去掉 --dry-run。
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
MAPPING="${MAPPING:-$ROOT/mapping/books.csv}"
DEST="${DEST:-/data/easystudy/static}"
DRY_RUN="${DRY_RUN:-1}"
FILTER_BOOK_ID="${FILTER_BOOK_ID:-}"

if [[ ! -f "$MAPPING" ]]; then
  echo "missing $MAPPING (run 01-build-mapping.py)" >&2
  exit 1
fi

echo "DRY_RUN=$DRY_RUN DEST=$DEST FILTER_BOOK_ID=$FILTER_BOOK_ID"

python3 - "$MAPPING" "$DEST" "$DRY_RUN" "$FILTER_BOOK_ID" <<'PY'
import csv, os, sys, shutil
from pathlib import Path

mapping, dest, dry, filt = sys.argv[1], Path(sys.argv[2]), sys.argv[3] == "1", sys.argv[4]
ok = skip = fail = 0
with open(mapping, encoding="utf-8-sig") as fh:
    for row in csv.DictReader(fh):
        if filt and row["book_id"] != filt:
            continue
        src = Path(row["source_path"]) if row["source_path"] else None
        dst = Path(row["dest_path"])
        if not src or row["method"] == "missing":
            skip += 1
            continue
        if not src.exists():
            print("FAIL missing", src)
            fail += 1
            continue
        if dry:
            print("DRY", row["kind"], src, "->", dst, row["method"])
            ok += 1
            continue
        if row["kind"] == "book_images":
            dst.mkdir(parents=True, exist_ok=True)
            for p in src.iterdir():
                if p.suffix.lower() not in {".png", ".jpg", ".jpeg", ".webp"}:
                    continue
                target = dst / p.name
                if target.exists():
                    continue
                if row["method"] == "hardlink":
                    os.link(p, target)
                else:
                    shutil.copy2(p, target)
            ok += 1
            continue
        dst.parent.mkdir(parents=True, exist_ok=True)
        if dst.exists():
            skip += 1
            continue
        if row["method"] == "hardlink":
            os.link(src, dst)
        else:
            shutil.copy2(src, dst)
        ok += 1
print(f"done ok={ok} skip={skip} fail={fail}")
sys.exit(2 if fail else 0)
PY
