#!/usr/bin/env python3
"""Grep the decompiled corpus with context."""
import os, re, sys, glob

ROOT = "/opt/ws-remote/scripts/soleezz/rivals/analysis"

def files():
    return sorted(glob.glob(os.path.join(ROOT, "**", "*.lua"), recursive=True))

def scan(pattern, ctx=0, limit=200, flags=re.I):
    rx = re.compile(pattern, flags)
    hits = 0
    for f in files():
        try:
            lines = open(f, encoding="utf-8", errors="replace").read().split("\n")
        except Exception:
            continue
        for i, l in enumerate(lines):
            if rx.search(l):
                hits += 1
                if hits > limit:
                    return
                print("--- %s:%d" % (os.path.relpath(f, ROOT), i + 1))
                lo = max(0, i - ctx); hi = min(len(lines), i + ctx + 1)
                for j in range(lo, hi):
                    print("   %s" % lines[j][:220])

if __name__ == "__main__":
    pat = sys.argv[1]
    ctx = int(sys.argv[2]) if len(sys.argv) > 2 else 0
    lim = int(sys.argv[3]) if len(sys.argv) > 3 else 200
    scan(pat, ctx, lim)
