"""Diff current JxVoCongTruyenKy tree against the 2026-09-18 baseline."""
from __future__ import annotations

import csv
import hashlib
import os
from pathlib import Path

ROOT = Path(r"C:\JXVCTK\JxVoCongTruyenKy")
BASE = Path(__file__).resolve().parents[1] / "inventory.csv"


def sha256(path: Path, chunk: int = 1024 * 1024) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        while True:
            b = f.read(chunk)
            if not b:
                break
            h.update(b)
    return h.hexdigest()


def main() -> None:
    old = {}
    with BASE.open(encoding="utf-8") as f:
        for row in csv.DictReader(f):
            old[row["relpath"].replace("\\", "/")] = row

    now = {}
    for dirpath, _, filenames in os.walk(ROOT):
        for name in filenames:
            p = Path(dirpath) / name
            rel = str(p.relative_to(ROOT)).replace("\\", "/")
            now[rel] = p

    added = sorted(set(now) - set(old))
    removed = sorted(set(old) - set(now))
    changed = []
    for rel in sorted(set(now) & set(old)):
        digest = sha256(now[rel])
        if digest.lower() != (old[rel].get("sha256") or "").lower():
            changed.append((rel, old[rel].get("sha256"), digest, now[rel].stat().st_size))

    print(f"baseline files: {len(old)}")
    print(f"current files:  {len(now)}")
    print(f"added:   {len(added)}")
    print(f"removed: {len(removed)}")
    print(f"changed: {len(changed)}")
    watch = {
        "AutoUpdateVCTK.exe",
        "add.bat",
        "game.exe",
        "_AutoKimYen/KY_VCTK_CTCX_NEW.exe",
        "_VLAuto/VLAutoPr.exe",
        "_AutoVLBS/VLBS19/core.dll",
        "_AutoVLBS/VLBS19Dai/winmm.dll",
    }
    if added:
        print("\n== ADDED ==")
        for r in added:
            flag = " [WATCH]" if r in watch or any(r.endswith(w) for w in watch) else ""
            print(" +", r, flag)
    if removed:
        print("\n== REMOVED ==")
        for r in removed:
            print(" -", r)
    if changed:
        print("\n== CHANGED HASH ==")
        for rel, oldh, newh, size in changed:
            flag = " [WATCH]" if rel in watch else ""
            print(f" * {rel}{flag}")
            print(f"     old {oldh}")
            print(f"     new {newh}  size={size}")
    if not added and not removed and not changed:
        print("\nNo differences vs 2026-09-18 baseline.")


if __name__ == "__main__":
    main()
