#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""scan_dir.py — quét keyword (plain + XOR55) trên mọi file trong thư mục app."""
import sys, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from scan_env_checks import KEYWORDS

root = sys.argv[1]
report = sys.argv[2] if len(sys.argv) > 2 else None
lines = []
skip_ext = {'.png', '.jpg', '.jpeg', '.car', '.nib', '.ttf', '.otf', '.woff', '.woff2', '.gz', '.zip', '.mp3', '.mp4', '.wav'}
for dirpath, dirnames, filenames in os.walk(root):
    for fn in filenames:
        p = os.path.join(dirpath, fn)
        ext = os.path.splitext(fn)[1].lower()
        if ext in skip_ext:
            continue
        try:
            data = open(p, 'rb').read()
        except Exception:
            continue
        if len(data) < 16:
            continue
        x55 = bytes(b ^ 0x55 for b in data)
        for kw in KEYWORDS:
            hits = []
            i = 0
            while True:
                j = data.find(kw, i)
                if j < 0: break
                hits.append(('plain', j)); i = j + 1
            i = 0
            while True:
                j = x55.find(kw, i)
                if j < 0: break
                hits.append(('xor55', j)); i = j + 1
            if hits:
                rel = os.path.relpath(p, root)
                for tag, j in hits[:4]:
                    s = max(0, j - 40)
                    e = min(len(data), j + len(kw) + 60)
                    if tag == 'plain':
                        ctx = data[s:e]
                    else:
                        ctx = x55[s:e]
                    ctx = bytes(c if 32 <= c < 127 else 0x2e for c in ctx).decode('ascii', 'replace')
                    lines.append('%s %-6s %s @0x%x | ...%s...' % (rel, tag, kw.decode('utf-8', 'replace')[:26], j, ctx))
out = '\n'.join(lines)
if report:
    open(report, 'w', encoding='utf-8').write(out)
    print('wrote', report, len(lines), 'hits')
else:
    import sys as _s
    _s.stdout.write(out)
