"""Audit every .SCN on the drive: which geometry does it need, and in what form
(VGF text / BGF binary / missing) does that geometry survive?"""
import os, re, sys
from collections import defaultdict

SDA4 = r"c:\VWE\TeslaRel410\sda4"

# index every VGF/BGF/VMF/BMF/TGA on the drive by lowercase basename
index = defaultdict(list)
for root, dirs, files in os.walk(SDA4):
    dirs[:] = [d for d in dirs if d.upper() not in ("EDITBACK", "RECYCLED")]
    for f in files:
        base, ext = os.path.splitext(f.lower())
        if ext in (".vgf", ".bgf", ".vmf", ".bmf", ".tga", ".spl", ".bsl"):
            index[(base, ext)].append(os.path.join(root, f))

def parse_scene_refs(path):
    geos, mats, spls = [], set(), []
    geodir = matdir = None
    for raw in open(path, errors="replace"):
        line = raw.split("//")[0].split("#")[0].strip()
        if not line: continue
        t = line.split()
        k = t[0].upper()
        try:
            if k == "GEOMETRY": geodir = t[1]
            elif k == "MATERIAL": matdir = t[1]
            elif k in ("STATIC", "SCHILD", "DCHILD"):
                geos.append(t[1].lower())
            elif k == "DYNAMIC":
                geos.append(t[1].lower())
                spls.append(os.path.basename(t[3].replace("\\", "/")).lower())
            elif k == "MORPH":
                geos.append(t[1].lower())
        except IndexError:
            pass
    return geos, spls, geodir, matdir

scenes = []
for root, dirs, files in os.walk(SDA4):
    dirs[:] = [d for d in dirs if d.upper() not in ("EDITBACK", "RECYCLED")]
    for f in files:
        if f.lower().endswith(".scn"):
            scenes.append(os.path.join(root, f))

report = []
for s in sorted(scenes):
    geos, spls, geodir, matdir = parse_scene_refs(s)
    if not geos: continue
    uniq = sorted(set(g.split(":")[0] for g in geos))
    n_vgf = sum(1 for g in uniq if (g, ".vgf") in index)
    n_bgf = sum(1 for g in uniq if (g, ".bgf") in index and (g, ".vgf") not in index)
    n_missing = len(uniq) - n_vgf - n_bgf
    spl_missing = sum(1 for x in set(spls) if (os.path.splitext(x)[0], ".spl") not in index)
    rel = os.path.relpath(s, SDA4)
    report.append((rel, len(uniq), n_vgf, n_bgf, n_missing, spl_missing))

print(f"{'scene':<44} {'geo':>3} {'vgf':>3} {'bgf':>3} {'mis':>3} {'spl-':>4}")
full, partial, locked = 0, 0, 0
for rel, n, v, b, m, sm in report:
    tag = "FULL-VGF" if v == n else ("HAS-BGF" if m == 0 else "MISSING")
    if v == n: full += 1
    elif m == 0: locked += 1
    else: partial += 1
    print(f"{rel:<44} {n:>3} {v:>3} {b:>3} {m:>3} {sm:>4}  {tag}")
print(f"\n{len(report)} scenes with geometry: {full} fully VGF, {locked} need BGF, {partial} have missing geometry")
