"""Correction check for iis:2611.00067: the eight "renamed" theorems were not renamed.

Resolves every theorem in a Formal Conjectures file to its full Lean name, following nested
`namespace ... end` blocks, and reads the @[category ...] attribute above it.
Usage: python fc_nested_names.py [commit]   (default f606af1; fetches raw files from GitHub)
"""
import re, sys, urllib.request

COMMIT = sys.argv[1] if len(sys.argv) > 1 else "f606af1"
ENTRIES = [  # long-list id, FC file, long-list theorem name (without the outer ErdosN/GreenN namespace)
    ("IIS-L-00085", "ErdosProblems/601.lean", "Erdos601", "erdos_601.variants.omega_1_omega_plus_2"),
    ("IIS-L-01675", "ErdosProblems/1167.lean", "Erdos1167", "erdos_1167.variants.binary_colors"),
    ("IIS-L-01676", "ErdosProblems/1167.lean", "Erdos1167", "erdos_1167.variants.infinite_targets"),
    ("IIS-L-01677", "ErdosProblems/1167.lean", "Erdos1167", "erdos_1167.variants.r_eq_two"),
    ("IIS-L-01779", "ErdosProblems/1169.lean", "Erdos1169", "erdos_1169.variants.finite_blue_target"),
    ("IIS-L-01824", "ErdosProblems/70.lean", "Erdos70", "erdos_70.variants.omega_one"),
    ("IIS-L-01922", "ErdosProblems/70.lean", "Erdos70", "erdos_70.variants.omega_times_two_four"),
    ("IIS-L-01928", "GreensOpenProblems/24.lean", "Green24", "variants.conjecture"),
]

def theorems(src):
    """Yield (full name, category, line) for every theorem, tracking nested namespaces."""
    stack, cat = [], None
    for i, line in enumerate(src.splitlines(), 1):
        if m := re.match(r"\s*namespace\s+(\S+)", line):
            stack.append(m.group(1))
        elif m := re.match(r"\s*end\s+(\S+)\s*$", line):
            if stack and stack[-1] == m.group(1):
                stack.pop()
        elif m := re.match(r"\s*@\[category\s+([^,\]]+)", line):
            cat = m.group(1).strip()
        elif m := re.match(r"\s*theorem\s+(\S+)", line):
            yield ".".join(stack + [m.group(1)]), cat, i
            cat = None

def main():
    cache, ok = {}, 0
    for lid, path, outer, name in ENTRIES:
        if path not in cache:
            url = f"https://raw.githubusercontent.com/google-deepmind/formal-conjectures/{COMMIT}/FormalConjectures/{path}"
            cache[path] = {n: (c, l) for n, c, l in theorems(urllib.request.urlopen(url).read().decode())}
        full = f"{outer}.{name}"
        hit = cache[path].get(full)
        print(f"{lid}  {full:<55} {'line %d, %s' % (hit[1], hit[0]) if hit else 'NOT FOUND'}")
        ok += bool(hit) and hit[0] == "research open"
    print(f"{ok}/{len(ENTRIES)} resolve under their long-list name and are tagged research open at {COMMIT}")
    assert ok == len(ENTRIES)

if __name__ == "__main__":
    main()
