from pathlib import Path
import hashlib
import difflib

root = Path(__file__).resolve().parent / 'Картотека'
left = root / 'Кодекс оружий'
right = root / 'Кодекс Снаряжения и Оружия'

report = []

def file_hash(p: Path) -> str:
    h = hashlib.sha256()
    with p.open('rb') as f:
        for chunk in iter(lambda: f.read(8192), b''):
            h.update(chunk)
    return h.hexdigest()

left_files = {p.relative_to(left).as_posix(): p for p in left.rglob('*') if p.is_file()}
right_files = {p.relative_to(right).as_posix(): p for p in right.rglob('*') if p.is_file()}

all_keys = sorted(set(left_files) | set(right_files))

summary = {'only_left': [], 'only_right': [], 'same': [], 'diff': []}

for key in all_keys:
    l = left_files.get(key)
    r = right_files.get(key)
    if l and not r:
        summary['only_left'].append(key)
        report.append(f"ONLY LEFT: {key} -> {l}")
    elif r and not l:
        summary['only_right'].append(key)
        report.append(f"ONLY RIGHT: {key} -> {r}")
    else:
        # both exist
        lh = file_hash(l)
        rh = file_hash(r)
        if lh == rh:
            summary['same'].append(key)
            report.append(f"SAME: {key} (sha256 {lh[:8]})")
        else:
            summary['diff'].append(key)
            report.append(f"DIFF: {key}\n  left: {l} (sha256 {lh[:8]}, {l.stat().st_size} bytes)\n  right: {r} (sha256 {rh[:8]}, {r.stat().st_size} bytes)")
            # if both are text, include textual diff
            try:
                ltext = l.read_text(encoding='utf-8')
                rtext = r.read_text(encoding='utf-8')
                ld = list(difflib.unified_diff(ltext.splitlines(), rtext.splitlines(), fromfile='left/'+key, tofile='right/'+key, lineterm=''))
                if ld:
                    report.append('\n'.join(ld[:200]))
                else:
                    report.append('  (binary or no textual diff)')
            except Exception as e:
                report.append(f'  (binary or read error: {e})')

out = Path(__file__).resolve().parent / 'codex_compare_report.txt'
out.write_text('\n'.join(report), encoding='utf-8')
print(f"Compared {len(all_keys)} paths: {len(summary['same'])} same, {len(summary['diff'])} different, {len(summary['only_left'])} only-left, {len(summary['only_right'])} only-right")
print(f"Report written to {out}")
