#!/usr/bin/env python3
"""Read-only backup audit and self-contained candidate staging; no match claims.

Clang is used ONLY for syntax/declaration inspection. Actual compiler jobs and
original-byte comparisons go through scripts/verify and the backend owner.
The missing historical include is replaced only by explicit fixed-width aliases;
unknown types, global definitions, assembly, other directives and unaddressed
externals are deferred rather than guessed.
"""
import concurrent.futures
import hashlib
import json
import os
import pathlib
import re
import subprocess

ROOT = pathlib.Path(__file__).resolve().parents[1]
BACKUP = pathlib.Path(os.environ.get('PC_DECOMP_BACKUP_ROOT', '/home/keegan/Repos/pc_decomp_backup'))
OUT = ROOT / '.work/backup-import'
OUT.mkdir(parents=True, exist_ok=True)
known = json.loads((ROOT / '.work/ten-functions/live-rpc.json').read_text())
functions = {f['address'].lower().removeprefix('0x'): f for p in known['atlas'] for f in p['rows']}
protected_path = OUT/'protected.json'
protected = set(json.loads(protected_path.read_text())) if protected_path.exists() else {p.stem for p in (ROOT / 'src/functions').glob('*.cpp')}
if not protected_path.exists(): protected_path.write_text(json.dumps(sorted(protected))+'\n')
blocked = {'00403960', '00405bf0', '00444d10'}
aliases = {
    'byte': 'unsigned char', 'sbyte': 'signed char', 'ushort': 'unsigned short',
    'uint': 'unsigned int', 'ulong': 'unsigned long', 'undefined': 'unsigned char',
    'undefined1': 'unsigned char', 'undefined2': 'unsigned short', 'undefined4': 'unsigned int',
    'undefined8': 'unsigned __int64', 'longlong': '__int64', 'ulonglong': 'unsigned __int64',
    'int8_t': 'signed char', 'int16_t': 'short', 'int32_t': 'int', 'int64_t': '__int64',
    'uint8_t': 'unsigned char', 'uint16_t': 'unsigned short', 'uint32_t': 'unsigned int',
    'uint64_t': 'unsigned __int64', 'uintptr_t': 'unsigned int',
}

def audit(path):
    raw = path.read_bytes()
    row = dict(path=str(path.relative_to(BACKUP)), sha256=hashlib.sha256(raw).hexdigest())
    found = re.search(r'004[0-9a-fA-F]{5}', path.stem)
    if not found: return dict(row, reason='no address in filename')
    address = found[0].lower(); row['address'] = address
    if address not in functions: return dict(row, reason='not a current function entry')
    if address in blocked: return dict(row, reason='patched Ghidra body; preserve analysis')
    if address in protected: return dict(row, reason='existing candidate protected')
    source = raw.decode('utf-8', errors='replace')
    if re.search(r'__asm|\basm\s*\(|\bnaked\b|_emit\b', source):
        return dict(row, reason='assembly/raw emission; reference only')
    source = re.sub(r'^\s*#include\s+"../../include/game_types.h"\s*$', '', source, flags=re.M)
    source = re.sub(r'/\*.*?\*/|//[^\n]*', '', source, flags=re.S)
    if '#' in source: return dict(row, reason='other preprocessor/dependency input')
    names = re.findall(r'\b([A-Za-z_]\w*004[0-9a-fA-F]{5}\w*)\s*\([^;{}]*\)\s*\{', source)
    names = [n for n in names if address in n.lower()]
    if len(names) != 1: return dict(row, reason='no unique addressed definition')
    source = re.sub(r'\b' + re.escape(names[0]) + r'\b', 'GEX_Target', source)
    source = re.sub(r'\bPDA_CDECL\b', '__cdecl', source)
    if re.search(r'__stdcall|__fastcall|__thiscall|PDA_', source):
        return dict(row, reason='unsupported calling convention/macro')
    prefix = ''.join(f'typedef {value} {name};\n' for name,value in aliases.items()
                     if re.search(r'\b'+name+r'\b', source))
    source = (f'// Adapted from pc_decomp_backup/{row["path"]}\n'
              f'// Historical source SHA256: {row["sha256"]}\n' + prefix +
              'extern "C" {\n' + source.strip() + '\n}\n')
    stage = OUT / 'candidates' / address / (row['sha256'][:24]+'.cpp')
    stage.parent.mkdir(parents=True, exist_ok=True); stage.write_text(source)
    args = ['clang++', '-target', 'i686-pc-windows-msvc', '-std=c++98', '-fms-extensions',
            '-fsyntax-only', '-ferror-limit=3', '-Wno-everything', '-Xclang', '-ast-dump=json', str(stage)]
    try: result = subprocess.run(args, capture_output=True, text=True, timeout=15)
    except subprocess.TimeoutExpired: return dict(row, reason='syntax inspection timeout')
    if result.returncode:
        errors = [line.split('error:',1)[1].strip() for line in result.stderr.splitlines() if 'error:' in line]
        return dict(row, reason='unresolved syntax/types/declarations', diagnostic=errors[:3])
    ast = json.loads(result.stdout); bindings = {}; bodies = []; externalize = []
    def declarations(node):
        for item in node.get('inner', []):
            if item.get('kind') == 'LinkageSpecDecl': yield from declarations(item)
            else: yield item
    for item in declarations(ast):
        kind = item.get('kind'); name = item.get('name', '')
        if kind == 'FunctionDecl':
            if any(i.get('kind')=='CompoundStmt' for i in item.get('inner', [])):
                bodies.append(name); continue
        elif kind == 'VarDecl':
            if item.get('storageClass') != 'extern':
                if item.get('init') or item.get('storageClass') == 'static' or not re.search(r'004[0-9a-fA-F]{5}(?:_|$)',name):
                    return dict(row, reason='global definition needs separate data reconstruction')
                # A single-declaration extern-C specification can omit storageClass
                # in Clang's AST. Make all address-named, uninitialized declarations
                # explicit imports; this TU does not reconstruct original data.
                externalize.append((item['range']['begin']['offset'], item['range']['end']['offset'] + item['range']['end']['tokLen']))
        else: continue
        if name == 'GEX_Target': continue
        address_match = re.search(r'(004[0-9a-fA-F]{5})(?:_|$)', name)
        if not address_match: return dict(row, reason='external without explicit original address', external=name)
        target = address_match[1].lower()
        if not 0x400000 <= int(target,16) <= 0x4fbdff:
            return dict(row, reason='external outside image', external=name)
        mangled = item.get('mangledName', '')
        if mangled != '_'+name: return dict(row, reason='non-C external linkage', external=name)
        bindings[mangled] = target
    if bodies != ['GEX_Target']: return dict(row, reason='multiple/helper definitions', definitions=bodies)
    # A placeholder only counts if the whole pinned original body really is tiny.
    tiny = re.search(r'GEX_Target\([^{}]*\)\s*\{\s*(?:return\s+(?:0|1)\s*;)?\s*\}', source)
    if tiny and functions[address]['size'] > 8:
        return dict(row, reason='placeholder stub for nontrivial original body')
    encoded = source.encode()
    changes = {}
    for offset,end in set(externalize):
        if re.search(rb'extern\s+"C"\s*$', encoded[:offset]):
            changes[offset] = b'{ extern '
            changes[encoded.index(b';', end)+1] = b' }'
        else: changes[offset] = b'extern '
    for offset,insert in sorted(changes.items(), reverse=True): encoded = encoded[:offset] + insert + encoded[offset:]
    source = encoded.decode(); stage.write_text(source)
    if changes:
        checked=subprocess.run(args[:args.index('-Xclang')]+[str(stage)],capture_output=True,text=True,timeout=15)
        if checked.returncode: return dict(row,reason='external declaration adaptation failed',diagnostic=checked.stderr[:500])
    return dict(row, reason='staged', externalizedDeclarations=len(externalize), candidate=str(stage.relative_to(ROOT)),
                candidateHash=hashlib.sha256(source.encode()).hexdigest(), bindings=bindings,
                originalSize=functions[address]['size'])

paths = sorted((BACKUP / 'src/functions').glob('*.cpp'))
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
    rows = list(pool.map(audit, paths))
(OUT / 'audit.json').write_text(json.dumps(rows, indent=2)+'\n')
from collections import Counter
print(json.dumps(dict(Counter(r['reason'] for r in rows)), indent=2))
print('Eligible unique addresses:',len({r['address'] for r in rows if r['reason']=='staged'}))
