#!/usr/bin/env python3
import sys, json, subprocess, urllib.parse

def sg(q):
    url = "https://sourcegraph.com/search/stream?q=" + urllib.parse.quote(q) + "&v=V3&t=literal"
    out = subprocess.run(["curl","-sS","-m","40","-A","Mozilla/5.0",url], capture_output=True, text=True).stdout
    matches = []
    total = None
    for line in out.splitlines():
        if line.startswith("data: "):
            try:
                d = json.loads(line[6:])
            except Exception:
                continue
            if isinstance(d, list):
                for m in d:
                    if isinstance(m, dict) and "repository" in m:
                        matches.append(m)
            elif isinstance(d, dict) and "matchCount" in d and d.get("done"):
                total = d.get("matchCount")
    return total, matches

if __name__ == "__main__":
    for q in sys.argv[1:]:
        total, matches = sg(q)
        print(f"==== query: {q} | matchCount={total} ====")
        seen = set()
        for m in matches[:40]:
            repo = m.get("repository")
            path = m.get("path")
            key = (repo, path)
            if key in seen: continue
            seen.add(key)
            lines = []
            for lm in m.get("lineMatches", [])[:3]:
                lines.append(lm.get("line","")[:160])
            print(f"  {repo} | {path}")
            for l in lines:
                print(f"      {l}")
