#!/usr/bin/env python3
"""Convert an assembled release tree to npm packages and wheels; never publishes.

Run on the final runtime tree after any platform signing or notarization.
No stripping, patching or repair is allowed.
"""
import argparse
import base64
import csv
import hashlib
import io
import json
import re
from pathlib import Path
import shutil
import struct
import subprocess
import tempfile
import tomllib
import zipfile

from release_inventory import registry_runtime
from runtime_platform import check_runtime_platform, verify_macos_manifest

ROOT = Path(__file__).resolve().parents[1]
# npm provenance (trusted publishing) requires the package's repository metadata
# to name the public repository that publishes it, case-sensitively.
REPOSITORY = {'type': 'git', 'url': 'git+https://github.com/voyager-so/vork.git'}
TARGETS = {
    'linux-x64': ('linux', 'x64', 'manylinux_2_35_x86_64', 'sys_platform == "linux" and platform_machine == "x86_64"'),
    'darwin-arm64': ('darwin', 'arm64', None, 'sys_platform == "darwin" and platform_machine == "arm64"'),
    'windows-x64': ('win32', 'x64', 'win_amd64', 'sys_platform == "win32" and platform_machine == "AMD64"'),
}


def update_advice(policy):
    advice = policy.get('vorkUpdate', {})
    if (not isinstance(advice, dict) or set(advice) - {'reason', 'regression'}
            or not isinstance(advice.get('reason', ''), str)
            or len(advice.get('reason', '')) > 240
            or any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in advice.get('reason', ''))
            or not isinstance(advice.get('regression', False), bool)):
        raise ValueError('vorkUpdate requires a single-line reason (at most 240 characters) and boolean regression')
    return advice


def wheel(output, name, version, tag, files):
    normalized = name.replace('-', '_')
    info = f'{normalized}-{version}.dist-info'
    files = dict(files)
    files[f'{info}/METADATA'] = (f'Metadata-Version: 2.4\nName: {name}\nVersion: {version}\nRequires-Python: >=3.11\nLicense-Expression: LicenseRef-vork-Preview\nLicense-File: LICENSE\nDescription-Content-Type: text/markdown\n' + '\n' + ((ROOT / 'packages/python/README.md').read_text() if name == 'vork' else 'Native vork engine for internal qualification.\n')).encode()
    files[f'{info}/licenses/LICENSE'] = (ROOT / 'LICENSE').read_bytes()
    files[f'{info}/WHEEL'] = f'Wheel-Version: 1.0\nGenerator: vork\nRoot-Is-Purelib: {str(tag == "any").lower()}\nTag: py3-none-{tag}\n'.encode()
    records = []
    path = output / f'{normalized}-{version}-py3-none-{tag}.whl'
    with zipfile.ZipFile(path, 'w', zipfile.ZIP_DEFLATED) as archive:
        for name, source in sorted(files.items()):
            data = source.read_bytes() if isinstance(source, Path) else source
            item = zipfile.ZipInfo(name)
            item.compress_type = zipfile.ZIP_DEFLATED
            mode = (source.stat().st_mode & 0o777) if isinstance(source, Path) else 0o644
            item.external_attr = (0o100000 | mode) << 16
            archive.writestr(item, data)
            digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b'=').decode()
            records.append((name, 'sha256=' + digest, len(data)))
        record = io.StringIO(newline='')
        writer = csv.writer(record)
        writer.writerows(records + [(f'{info}/RECORD', '', '')])
        archive.writestr(f'{info}/RECORD', record.getvalue())
    print(f'{path}: {path.stat().st_size} bytes')


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--tree', type=Path, required=True, help='extracted complete platform runtime')
    p.add_argument('--platform', choices=TARGETS, required=True)
    p.add_argument('--output', type=Path, required=True)
    a = p.parse_args()
    version = tomllib.loads((ROOT / 'Cargo.toml').read_text())['workspace']['package']['version']
    if '-' in version:
        p.error('registry candidate must use a final numeric version; private registries isolate rehearsals')
    tree = a.tree.resolve()
    binary = 'vork.exe' if a.platform == 'windows-x64' else 'vork'
    try:
        runtime = registry_runtime(tree, a.platform)
    except (ValueError, OSError) as error:
        p.error(str(error))
    if json.loads((tree / 'sdk/package.json').read_text())['version'] != version:
        p.error('release SDK version does not match Cargo version')
    # The native executable owns immutable build identity; a version alone can
    # describe many different SDK revisions. Require the full source commit
    # before combining their bytes.
    commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
    try:
        reported = subprocess.check_output([str(tree / binary), '--version'], text=True)
        match = re.fullmatch(r'vork ([^ ]+) \(commit ([0-9a-f]{40}); API v2\)\s*', reported)
        if not match or match[1] != version:
            p.error('native runtime lacks current version and source identity')
        native_commit = match[2]
    except (OSError, subprocess.CalledProcessError) as error:
        p.error(f'cannot verify native runtime source identity: {error}')
    if native_commit != commit:
        p.error(f'native source {native_commit} does not match SDK source {commit}')
    if subprocess.check_output(['git', 'status', '--porcelain', '--untracked-files=no', '--',
                                'packages/ts', 'packages/python', 'packages/create-vork', 'Cargo.toml',
                                'scripts/package-registries', 'scripts/registry-cli.cjs', 'scripts/release_inventory.py',
                                'dist/archive-inputs.json', 'dist/example-payload.txt'], cwd=ROOT, text=True).strip():
        p.error('registry packaging requires committed SDK and packaging sources')
    header = (tree / binary).read_bytes()
    if a.platform == 'linux-x64' and not (header[:5] == b'\x7fELF\x02' and struct.unpack_from('<H', header, 18)[0] == 62):
        p.error('expected an x86-64 ELF engine')
    if a.platform == 'darwin-arm64' and not (header[:4] == b'\xcf\xfa\xed\xfe' and struct.unpack_from('<I', header, 4)[0] == 0x100000c):
        p.error('expected an arm64 Mach-O engine')
    if a.platform == 'windows-x64':
        pe = struct.unpack_from('<I', header, 0x3c)[0]
        if header[:2] != b'MZ' or header[pe:pe+6] != b'PE\0\0\x64\x86':
            p.error('expected an x86-64 PE engine')
    a.output.mkdir(parents=True, exist_ok=True)
    os_name, cpu, tag, _ = TARGETS[a.platform]
    try:
        minimum = check_runtime_platform(runtime.values(), a.platform)
        if a.platform == 'darwin-arm64':
            verify_macos_manifest(tree)
    except (ValueError, OSError) as error:
        p.error(str(error))
    if a.platform == 'darwin-arm64':
        tag = f'macosx_{minimum[0]}_{minimum[1]}_arm64'
    with tempfile.TemporaryDirectory() as tmp:
        stage = Path(tmp)
        native = stage / 'native'
        native.mkdir()
        # Materialize internal links with identical target bytes for npm and wheels.
        for name, source in runtime.items():
            dest = native / 'runtime' / name
            dest.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(source, dest)
        native_meta = dict(name=f'@voyager-so/vork-{a.platform}', version=version, os=[os_name], cpu=[cpu], license='SEE LICENSE IN runtime/LICENSE', repository=REPOSITORY)
        if a.platform == 'linux-x64':
            native_meta['libc'] = ['glibc']
        (native / 'package.json').write_text(json.dumps(native_meta))
        subprocess.run([shutil.which('npm'), 'pack', '--ignore-scripts', '--pack-destination', str(a.output.resolve())], cwd=native, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        main = stage / 'main'
        shutil.copytree(ROOT / 'packages/ts/dist', main / 'dist')
        shutil.copy2(ROOT / 'packages/ts/scene.schema.json', main / 'scene.schema.json')
        shutil.copy2(ROOT / 'LICENSE', main / 'LICENSE')
        shutil.copy2(ROOT / 'scripts/registry-cli.cjs', main / 'cli.cjs')
        meta = json.loads((ROOT / 'packages/ts/package.json').read_text())
        for key in ('scripts', 'devDependencies'):
            meta.pop(key, None)
        (main / 'README.md').write_text('# vork\n\nNative renderer and TypeScript SDK. Install with `npm install @voyager-so/vork`, then run `npx vork init my-shot`. Follow init\'s printed next steps in my-shot. The default `std/final` first render is warmed by setup; use `--profile std/draft` for quicker previews. Run `npx vork setup` explicitly after upgrades or driver changes; setup can take minutes and prints progress. Import the SDK from `@voyager-so/vork`. Keep optional dependencies enabled; reinstall dependencies on each machine. Requires Node 22.18+ (older Node emits EBADENGINE warnings; upgrade, or run TypeScript source with node --experimental-strip-types scene.ts where supported), a supported GPU and its drivers; Linux/Windows video also needs ffmpeg. See https://github.com/voyager-so/vork for platform requirements and examples.\n')
        meta.update(description='Native vork renderer, TypeScript SDK and scene schema', version=version, bin={'vork': 'cli.cjs'}, files=['dist', 'cli.cjs', 'LICENSE', 'README.md', 'scene.schema.json'], optionalDependencies={f'@voyager-so/vork-{t}': version for t in TARGETS}, repository=REPOSITORY)
        meta['vorkUpdate'] = update_advice(json.loads((ROOT / 'dist/release.json').read_text()))
        meta['exports']['./package.json'] = './package.json'
        (main / 'package.json').write_text(json.dumps(meta, indent=2) + '\n')
        subprocess.run([shutil.which('npm'), 'pack', '--ignore-scripts', '--pack-destination', str(a.output.resolve())], cwd=main, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        creator = stage / 'creator'
        creator.mkdir()
        shutil.copy2(ROOT / 'packages/create-vork/cli.cjs', creator / 'cli.cjs')
        shutil.copy2(ROOT / 'packages/create-vork/README.md', creator / 'README.md')
        shutil.copy2(ROOT / 'LICENSE', creator / 'LICENSE')
        (creator / 'package.json').write_text(json.dumps(dict(name='create-vork', version=version, description='Create an offline vork rendering project', bin={'create-vork': 'cli.cjs'}, engines={'node': '>=22.18'}, license='SEE LICENSE IN LICENSE', dependencies={'@voyager-so/vork': version}, repository=REPOSITORY), indent=2) + '\n')
        subprocess.run([shutil.which('npm'), 'pack', '--ignore-scripts', '--pack-destination', str(a.output.resolve())], cwd=creator, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    module = 'vork_native_' + a.platform.replace('-', '_')
    wheel(a.output, 'vork-native-' + a.platform, version, tag,
          {f'{module}/__init__.py': b''} | {f'{module}/runtime/{n}': f for n, f in runtime.items()})
    python = {f'vork/{f.relative_to(ROOT / "packages/python/vork").as_posix()}': f for f in (ROOT / 'packages/python/vork').rglob('*') if f.is_file() and '__pycache__' not in f.parts}
    wheel(a.output, 'vork', version, 'any', python)


if __name__ == '__main__':
    main()
