"""Generate an Epic-adapted compatibility profile and build the native host.

Derives the adapter contract from the user's OWN locally installed Epic FM27
engine DLL (game_plugin.dll). No game bytes leave this machine; the generated
profile stays under private/ and build/.

Usage:
  python scripts/build_native_epic.py --game-root "D:/Epic Games/Guinnessc2uBe"
  (run inside an x64 MSVC developer environment, cl.exe required)
"""
import argparse
import hashlib
import json
import shutil
import struct
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'scripts'))
from profile_header import header  # noqa: E402

STEAM_METADATA = ROOT / 'native/profile_metadata.json'
JMP = 0xE9


class Pe:
    def __init__(self, path):
        self.path = Path(path)
        self.raw = self.path.read_bytes()
        if self.raw[:2] != b'MZ':
            raise ValueError('Not a PE file')
        peoff = struct.unpack_from('<I', self.raw, 0x3c)[0]
        if self.raw[peoff:peoff + 4] != b'PE\0\0':
            raise ValueError('Invalid PE signature')
        self.nsec = struct.unpack_from('<H', self.raw, peoff + 6)[0]
        opt_size = struct.unpack_from('<H', self.raw, peoff + 20)[0]
        self.opt = peoff + 24
        self.image_base = struct.unpack_from('<Q', self.raw, self.opt + 24)[0]
        self.entrypoint = struct.unpack_from('<I', self.raw, self.opt + 16)[0]
        self.size_of_image = struct.unpack_from('<I', self.raw, self.opt + 56)[0]
        self.size_of_headers = struct.unpack_from('<I', self.raw, self.opt + 60)[0]
        self.sections = []
        for i in range(self.nsec):
            base = self.opt + opt_size + i * 40
            vsize, rva, rsize, roff = struct.unpack_from('<IIII', self.raw, base + 8)
            chars = struct.unpack_from('<I', self.raw, base + 36)[0]
            self.sections.append({'rva': rva, 'vsize': vsize, 'rsize': rsize,
                                  'roff': roff, 'flags': chars})

    def read_rva(self, rva, size):
        if rva + size <= self.size_of_headers:
            return bytes(self.raw[rva:rva + size])
        for s in self.sections:
            if s['rva'] <= rva and rva + size <= s['rva'] + s['rsize']:
                off = s['roff'] + rva - s['rva']
                return bytes(self.raw[off:off + size])
        return None

    def mapped(self, rva, size):
        for s in self.sections:
            if s['rva'] <= rva and rva + size <= s['rva'] + max(s['vsize'], s['rsize']):
                return True
        return False

    def imports(self):
        """Return {dll!name: [iat thunk rvas]} parsed through mapped reads."""
        imp_rva = struct.unpack_from('<I', self.raw, self.opt + 112 + 8)[0]
        result = {}
        for i in range(8192):
            desc = self.read_rva(imp_rva + i * 20, 20)
            if desc is None:
                break
            oft, _ts, _fwd, name_rva, fthunk = struct.unpack('<IIIII', desc)
            if not name_rva and not fthunk:
                break
            dll = b''
            for j in range(256):
                c = self.read_rva(name_rva + j, 1)
                if not c or c == b'\0':
                    break
                dll += c
            dll = dll.decode('latin1').lower()
            if not dll:
                break
            src = oft or fthunk
            j = 0
            while j < 65536:
                b = self.read_rva(src + 8 * j, 8)
                if b is None:
                    break
                (value,) = struct.unpack('<Q', b)
                if value == 0:
                    break
                if value & (1 << 63):
                    name = '#' + str(value & 0xffff)
                else:
                    name = b''
                    k = 2
                    while k < 65536:
                        c = self.read_rva(value + k, 1)
                        if not c or c == b'\0':
                            break
                        name += c
                        k += 1
                    name = name.decode('latin1')
                result.setdefault(dll + '!' + name, []).append(fthunk + 8 * j)
                j += 1
        return result


def tls_directory(pe):
    tls_rva = struct.unpack_from('<I', pe.raw, pe.opt + 112 + 9 * 8)[0]
    blob = pe.read_rva(tls_rva, 40)
    if blob is None:
        raise ValueError('TLS directory unreadable')
    sb, eb, idx, cb, zero_fill, _ch = struct.unpack('<QQQQII', blob)
    base = pe.image_base
    callbacks = []
    i = 0
    while True:
        b = pe.read_rva(cb - base + 8 * i, 8)
        if b is None:
            break
        (v,) = struct.unpack('<Q', b)
        if v == 0:
            break
        callbacks.append(v - base)
        i += 1
    return {'raw_rva': sb - base, 'raw_size': eb - sb, 'index_rva': idx - base,
            'zero_fill': zero_fill}, callbacks


def build_profile(pe, steam_md):
    dll_sha = hashlib.sha256(pe.raw).hexdigest()
    profile = {
        'id': 'fm27_epic_2494687_adapter_v1',
        'reference_sha256': dll_sha,
        'image_base': pe.image_base,
        'entrypoint_rva': pe.entrypoint,
        'minimum_image_size': pe.size_of_image,
        'sections': [{'rva': s['rva'], 'memory_flags': s['flags'] & 0xe0000000}
                     for s in pe.sections],
        'tls': None, 'tls_callbacks': None,
        'imports': [], 'ranges': [], 'data_addresses': [],
        # The Epic build does not expose the Steam activation state word; it exports
        # WaitForActivation() instead, which returns once the engine reports ready.
        'activation': {'kind': 'export', 'name': 'WaitForActivation'},
    }
    tls, callbacks = tls_directory(pe)
    profile['tls'] = tls
    profile['tls_callbacks'] = callbacks

    imports = pe.imports()
    unmatched = []
    for item in steam_md['imports']:
        key = item['dll'].lower() + '!' + item['name']
        thunks = imports.get(key)
        if thunks and item['rva'] in thunks:
            profile['imports'].append(item)
        else:
            unmatched.append(item['dll'] + '!' + item['name'])
    print(f"imports kept identical to Steam layout: {len(profile['imports'])}/{len(steam_md['imports'])}")
    if unmatched:
        print(f"  replaced with Epic-derived anchors: {len(unmatched)}")
    # Anchor every remaining Epic import symbol so the gate still binds the IAT.
    for key, thunks in sorted(imports.items()):
        if key.startswith('msvcp140') or key.startswith('vcruntime140') or key.startswith('kernel32'):
            for t in thunks:
                dll_name, name = key.split('!', 1)
                profile['imports'].append({'dll': dll_name, 'name': name, 'rva': t})
    # de-duplicate
    seen = set()
    dedup = []
    for item in profile['imports']:
        k = (item['dll'], item['name'], item['rva'])
        if k not in seen:
            seen.add(k)
            dedup.append(item)
    profile['imports'] = dedup
    print(f"total import anchors: {len(dedup)}")

    jmp_moves = []
    for item in steam_md['ranges']:
        rva, size = item['rva'], item['size']
        epic = pe.read_rva(rva, size)
        entry = {'rva': rva, 'size': size}
        if epic is not None and hashlib.sha256(epic).hexdigest() == item['sha256']:
            pass  # byte-identical, keep anchor as-is
        elif size == 5 and epic and epic[0] == JMP:
            rel = struct.unpack('<i', epic[1:5])[0]
            target = rva + 5 + rel
            moved = pe.read_rva(target, size)
            if moved is None:
                raise ValueError(f'jmp target unmapped: {rva:#x} -> {target:#x}')
            entry = {'rva': target, 'size': size}
            jmp_moves.append((rva, target))
        # bytes come from the local Epic DLL either way
        b = pe.read_rva(entry['rva'], entry['size'])
        if b is None:
            raise ValueError(f'range unmapped on Epic dll: {entry["rva"]:#x}')
        entry['hex'] = b.hex()
        entry.pop('size')
        profile['ranges'].append(entry)
    if jmp_moves:
        print(f"range anchors moved via jmp thunks: {len(jmp_moves)}")
        for old, new in jmp_moves:
            print(f"  {old:#x} -> {new:#x}")

    unmapped_data = []
    for item in steam_md['data_addresses']:
        if pe.mapped(item['rva'], item['size']):
            profile['data_addresses'].append(item)
        else:
            unmapped_data.append(item['rva'])
    if unmapped_data:
        print(f"WARNING: {len(unmapped_data)} data anchors unmapped on Epic: "
              + ','.join(hex(r) for r in unmapped_data))
    print(f"data anchors kept: {len(profile['data_addresses'])}/{len(steam_md['data_addresses'])}")
    return profile


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--game-root', required=True, type=Path)
    args = parser.parse_args()
    dll = args.game_root / 'fm_Data/Plugins/x86_64/game_plugin.dll'
    if not dll.is_file():
        raise SystemExit(f'engine dll not found: {dll}')
    pe = Pe(dll)
    print(f'Epic dll: {dll}')
    print(f'  build anchor: entrypoint={pe.entrypoint:#x} image={pe.size_of_image:#x} base={pe.image_base:#x}')
    steam_md = json.loads(STEAM_METADATA.read_text(encoding='utf8'))
    profile = build_profile(pe, steam_md)

    native_out = ROOT / 'private/native'
    engine_out = ROOT / 'private/engine/fm27_native'
    native_out.mkdir(parents=True, exist_ok=True)
    engine_out.mkdir(parents=True, exist_ok=True)
    (native_out / 'engine_compat_profile.h').write_text(header(profile), encoding='ascii')
    (engine_out / 'engine_compat_profile.json').write_text(
        json.dumps(profile, indent=2), encoding='utf8')
    adapter = {
        'version': '27.0.1+2494687',
        'reference_dll_sha256': profile['reference_sha256'],
        'store': 'epic',
        'mapped_references': len(profile['ranges']),
        'unmapped_references': ['0xfb2580', '0x4a7c550'],
    }
    (engine_out / 'adapter_version.json').write_text(
        json.dumps(adapter, indent=2), encoding='utf8')
    print('Wrote private/native/engine_compat_profile.h')
    print('Wrote private/engine/fm27_native/engine_compat_profile.json')
    print('Wrote private/engine/fm27_native/adapter_version.json')

    # Compile the host with the Epic profile baked in.
    if not shutil.which('cl'):
        raise SystemExit('cl.exe not found; run inside an x64 MSVC developer environment.')
    build = ROOT / 'build/native'
    build.mkdir(parents=True, exist_ok=True)
    for path in (ROOT / 'native').iterdir():
        if path.suffix in {'.h', '.cpp', '.manifest'}:
            shutil.copy2(path, build / path.name)
    shutil.copy2(native_out / 'engine_compat_profile.h', build / 'engine_compat_profile.h')
    subprocess.run(['cl', '/nologo', '/O2', '/EHsc', '/std:c++17', 'desktop_host.cpp',
                    '/Fe:FM27Simulator.exe', '/Fo:desktop_host.obj', '/link', '/INCREMENTAL:NO',
                    '/MANIFEST:EMBED', '/MANIFESTINPUT:host.manifest', 'user32.lib'],
                   cwd=build, check=True)
    shutil.copy2(build / 'FM27Simulator.exe', engine_out / 'FM27Simulator.exe')
    print('Built private/engine/fm27_native/FM27Simulator.exe (Epic adapter)')

    # Immediate sanity check against the Epic dll.
    check = subprocess.run([str(engine_out / 'FM27Simulator.exe'), '--check-image', str(dll)],
                           capture_output=True, timeout=60, text=True)
    for line in check.stdout.splitlines():
        if 'native_engine_compatibility' in line:
            print('check-image:', line)


if __name__ == '__main__':
    main()
