"""Read local loading-screen rendering resources without opening the game process."""
import concurrent.futures, hashlib, importlib.machinery, json, re, struct, sys, zlib
from pathlib import Path

sys.stdout.reconfigure(encoding='utf-8')
scan=importlib.machinery.SourceFileLoader('local_resources','artifacts/ship-model-reference/scan-ship-assets.py').load_module()
output=Path('artifacts/loading-hologram-reference');output.mkdir(parents=True,exist_ok=True)
needles=re.compile(rb'loadingscreen|loading_screen|edgedetection|edge_detection|hologram(?!a)|outline|scanline',re.I)
rows=json.loads(Path('artifacts/ship-material-reference/materials-index.json').read_text())
rows=[r for r in rows if any('FragmentMaterial' in s for s in r['strings'][:4])]

def inspect(row):
    path=scan.root/f"{int(row['hash'][0],16):02x}"/row['hash']
    data=scan.decode(path,limit=262+65536)
    blocks=[('header',data)]
    for match in re.finditer(rb'\x78[\x01\x9c\xda]',data[:16384]):
        try:
            dec=zlib.decompressobj();plain=dec.decompress(data[match.start():],4*1024*1024)
            if len(plain)>64:blocks.append((str(match.start()),plain))
        except zlib.error:pass
    found=[]
    for name,plain in blocks:
        for match in needles.finditer(plain):
            start=max(0,match.start()-60);end=min(len(plain),match.end()+110)
            text=plain[start:end].replace(b'\0',b' ').decode('ascii',errors='replace')
            found.append(dict(block=name,offset=match.start(),context=text))
    if not found:return None
    # Preserve decoded candidates privately for inspection, with exact source hashes.
    full=scan.decode(path)
    (output/(row['hash']+'.fres')).write_bytes(full)
    return dict(resource=row['hash'],sourceSha256=hashlib.sha256(path.read_bytes()).hexdigest(),bytes=path.stat().st_size,
                names=row['strings'][:8],matches=found[:60])

found=[]
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
    for result in pool.map(inspect,rows):
        if result:found.append(result)
report=dict(scanned=len(rows),resources=found,gameProcessAccess=False,gameCallsInvoked=0)
(output/'material-evidence.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps(dict(scanned=len(rows),matched=len(found),loading=[r['resource'] for r in found if any('loading' in m['context'].lower() or 'edgedetection' in m['context'].lower() for m in r['matches'])])))
