"""So sanh NHANH cay JxVoCongTruyenKy hien tai vs inventory baseline 2026-09-18.
Muc dich: bat cac file MOI hoac doi kich thuoc (payload bi drop KHONG qua updater).
File giao nhau cung kich thuoc thi khong hash lai (UpdaterState.ini da bao phu cac file duoc quan ly).
"""
from __future__ import annotations

import csv
import hashlib
import os
from pathlib import Path

ROOT = Path(r"C:\JXVCTK\JxVoCongTruyenKy")
BASE = Path(r"C:\Projects\JX\security-baseline\2026-09-18-vctk\inventory.csv")
OUT = Path(r"C:\Projects\JX\security-baseline\2026-09-28-vctk\differences_vs_baseline.txt")


def sha256(p: Path) -> str:
    h = hashlib.sha256()
    with p.open("rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            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("\\", "/")] = (int(row["size"] or 0), (row.get("sha256") or "").lower())

    now = {}
    for dirpath, _, files in os.walk(ROOT):
        for n in files:
            p = Path(dirpath) / n
            rel = str(p.relative_to(ROOT)).replace("\\", "/")
            try:
                now[rel] = (p.stat().st_size, p)
            except OSError:
                pass

    added = sorted(set(now) - set(old))
    removed = sorted(set(old) - set(now))
    size_changed = sorted(r for r in set(now) & set(old) if now[r][0] != old[r][0])

    lines = ["# Fast diff vs baseline 2026-09-18 (chi hash file moi / doi size)", ""]
    lines.append("## ADDED ({0})".format(len(added)))
    for r in added:
        size, p = now[r]
        try:
            h = sha256(p)
        except OSError:
            h = "ERR"
        lines.append("+ {0} | {1} | {2}".format(r, size, h))
    lines.append("")
    lines.append("## REMOVED ({0})".format(len(removed)))
    for r in removed:
        lines.append("- {0}".format(r))
    lines.append("")
    lines.append("## SIZE-CHANGED ({0})".format(len(size_changed)))
    for r in size_changed:
        size, p = now[r]
        try:
            h = sha256(p)
        except OSError:
            h = "ERR"
        lines.append("* {0} | {1} -> {2} | {3}".format(r, old[r][0], size, h))
    OUT.write_text("\n".join(lines), encoding="utf-8")
    print("added:", len(added), "removed:", len(removed), "size-changed:", len(size_changed))
    print("output:", OUT)


if __name__ == "__main__":
    main()
