#!/opt/venv/bin/python3
# /data/www/_py/yyy_diff.py -> yyy_diff.py
# 사용처 /var/www/html/y/yyy_diff_simple.php
import argparse, html, os, sys
import difflib

MAX_READ = 2 * 1024 * 1024  # 2MB

def safe_read(path, max_bytes=MAX_READ):
    try:
        size = os.path.getsize(path)
        with open(path, 'rb') as f:
            data = f.read(min(size, max_bytes))
        return data.decode('utf-8', errors='replace').replace('\r\n', '\n')
    except Exception as e:
        return f"[[ 읽기 실패: {e} ]]"

def build_unified(left_txt, right_txt, left_label, right_label):
    l = left_txt.split('\n')
    r = right_txt.split('\n')
    diff = difflib.unified_diff(l, r, fromfile=left_label, tofile=right_label, lineterm='')
    return '\n'.join(diff)

def html_wrap(body,l, r):
    return f"""<!doctype html>
<html><head><meta charset="utf-8">
<title>Diff 비교</title>
<style>
body{{font-family:Consolas,Menlo,monospace;background:#1e1e1e;color:#ddd;margin:0}}
pre{{white-space:pre-wrap;word-break:break-word;margin:0;padding:12px}}
.header{{padding:10px;background:#111;border-bottom:1px solid #333}}
.badge{{display:inline-block;padding:2px 8px;border-radius:6px;margin-right:8px;font-size:12px}}
.badge-l{{background:#533;color:#f9c}}
.badge-r{{background:#235;color:#9df}}
.hint{{color:#aaa;font-size:12px;padding:8px 12px;border-top:1px solid #333}}
.add{{background:#003800}}
.rem{{background:#3a0000}}
.ctx{{background:#222}}
</style>
</head><body>
<div class="header">
  <span class="badge badge-l">left</span> {l}
  <span class="badge badge-r">right</span> {r}
</div>
{body}
<!-- div class="hint">Tip: 좌상단을 더블클릭하면 전체 선택 → 복사됩니다.</div-->
<script>
document.addEventListener('dblclick', ()=>{{
  const r=document.createRange();r.selectNode(document.body);
  const s=window.getSelection();s.removeAllRanges();s.addRange(r);
}});
</script>
</body></html>"""

def colorize_unified(diff_text):
    out = []
    for line in diff_text.split('\n'):
        esc = html.escape(line)
        if line.startswith('+++') or line.startswith('---') or line.startswith('@@'):
            out.append(f'<div class="ctx"><pre>{esc}</pre></div>')
        elif line.startswith('+'):
            out.append(f'<div class="add"><pre>{esc}</pre></div>')
        elif line.startswith('-'):
            out.append(f'<div class="rem"><pre>{esc}</pre></div>')
        else:
            out.append(f'<div class="ctx"><pre>{esc}</pre></div>')
    return '\n'.join(out)

def main():
    p = argparse.ArgumentParser()
    p.add_argument('--left', required=True)
    p.add_argument('--right', required=True)
    p.add_argument('--fmt', default='html', choices=['html','text'])
    args = p.parse_args()

    left_txt  = safe_read(args.left)
    right_txt = safe_read(args.right)

    uni = build_unified(left_txt, right_txt, args.left, args.right)
    if args.fmt == 'text':
        sys.stdout.write(uni if uni.strip() else "(파일 내용 동일)\n")
        return

    body = colorize_unified(uni if uni.strip() else "(파일 내용 동일)")
    sys.stdout.write(html_wrap(body,args.left, args.right))

if __name__ == '__main__':
    main()
