"""Package the verified 0.46.8 release; never upload or replace earlier builds."""
from pathlib import Path
from datetime import datetime, timezone
import hashlib
import argparse
import importlib.util
import json
import os
import shutil
import zipfile

ROOT = Path(__file__).resolve().parents[1]
VERSION = '0.46.8'
PLAYER = ROOT / 'Builds/Production0468Windows'
EVIDENCE = ROOT / 'Docs/Angel-Land-Story/qa/0.46.8'
PACKAGE = ROOT / f'Builds/AngelLandStory-Auralis-{VERSION}.zip'
PREVIOUS = ROOT / 'Builds/AngelLandStory-Auralis-0.46.5.zip'
PREVIOUS_SHA = '962079ad738e9a81f2bd9d91d98158f4a283031b44324d4face4a60340d7e6c3'
NOTES = EVIDENCE / 'RELEASE-NOTES.txt'


def require(value, message):
    if not value:
        raise RuntimeError(message)


def sha(path):
    with path.open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def read(path):
    return json.loads(path.read_text(encoding='utf-8-sig'))


def write_new(path, value):
    with path.open('x', encoding='utf-8', newline='\n') as stream:
        stream.write(json.dumps(value, ensure_ascii=False, indent=2) + '\n')


def copy_new(source, destination):
    with source.open('rb') as source_stream, destination.open('xb') as destination_stream:
        shutil.copyfileobj(source_stream, destination_stream, length=1024 * 1024)


def main():
    argparse.ArgumentParser(description=__doc__).parse_args()
    proof = read(EVIDENCE / 'release-validation.json')
    require(proof.get('version') == VERSION and proof.get('passed') is True,
            'The exact local release must pass its startup verification first.')
    require(proof.get('buildSucceeded') and proof.get('runtimeErrors') == 0
            and proof.get('failedChecks') == 0 and proof.get('nativeShutdownClean')
            and proof.get('sourceFreezeUnchanged') and proof.get('developmentBuild') is False,
            'Missing clean release build, source freeze or startup evidence.')
    payload = {name: sha(PLAYER / name) for name in proof['payloadSha256']}
    require(len(payload) >= 5 and payload == proof['payloadSha256'],
            'The player differs from the exact tested build.')
    require(VERSION.encode() in (PLAYER / 'AngelLandStory_Data/globalgamemanagers').read_bytes(),
            'Missing embedded release version.')
    require(NOTES.is_file() and (EVIDENCE / 'source-continuity.json').is_file(),
            'Missing consolidated content/continuity notes.')
    freeze = read(EVIDENCE / 'source-build.json')
    require(all(sha(ROOT / name) == digest for name, digest in freeze['sourceFiles'].items()),
            'Product sources changed after the compiled freeze.')
    startup_report = read(EVIDENCE / 'ReleaseStartup/report.json')
    require(len(startup_report['checks']) == 33 and startup_report['runtimeErrors'] == 0
            and all(check['passed'] for check in startup_report['checks']),
            'Actual startup report is incomplete or failed.')
    require(proof.get('runs') and len(proof['runs']) >= 2, 'Missing focused release suites.')
    for run in proof['runs']:
        report_path, process_path, log_path = (EVIDENCE / run[key] for key in ('report', 'process', 'nativeLog'))
        require(sha(report_path) == run['reportSha256'] and sha(process_path) == run['processSha256']
                and sha(log_path) == run['nativeLogSha256'], 'Focused release evidence changed.')
        process = read(process_path)
        require(process.get('passed') and process.get('exitCode') == 0 and process.get('version') == VERSION
                and process.get('assemblySha256') == payload['AngelLandStory_Data/Managed/Assembly-CSharp.dll'],
                'Focused suite does not identify this successful production player.')
    require(sha(PREVIOUS) == PREVIOUS_SHA, 'Preserve the previous version package.')
    pending = PACKAGE.with_suffix('.zip.pending')
    checksum = PACKAGE.with_suffix('.zip.sha256')
    for path in (PACKAGE, pending, checksum, PLAYER / 'STARTEN.txt', PLAYER / 'build-info.json',
                 PLAYER / 'AngelLandStoryIcon.png', EVIDENCE / 'shipping-sha256.json',
                 EVIDENCE / 'package-verification.json'):
        require(not os.path.lexists(path), 'Preserve existing output: ' + str(path))

    # Reuse only the established allowlist/hash helpers. No historical entrypoint runs.
    spec = importlib.util.spec_from_file_location('shipping0461', ROOT / 'Tools/Package-Production0461.py')
    shipping = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(shipping)
    shipping.PLAYER = PLAYER
    historical_excluded = shipping.excluded
    shipping.excluded = lambda relative: historical_excluded(relative) or relative.parts[0] in {'ReleaseStartup', 'GroundReview'}
    for license_file in (ROOT / 'ThirdParty/Fonts').iterdir():
        if license_file.is_file():
            require(sha(PLAYER / 'Licenses' / license_file.name) == sha(license_file), 'Missing font license.')
    info = {
        'version': VERSION, 'developmentBuild': False, 'saveVersion': 4,
        'builtUtc': proof['compiledUtc'], 'packagedUtc': datetime.now(timezone.utc).isoformat(),
        'payloadSha256': payload, 'validation': proof,
        'sourceContinuity': read(EVIDENCE / 'source-continuity.json'),
        'scope': 'Release 0.46.8: all exact-player suites are listed in validation. Earlier evidence retains its original build identity. No whole-campaign or human audio/style/controller acceptance.'}
    write_new(PLAYER / 'build-info.json', info)
    copy_new(NOTES, PLAYER / 'STARTEN.txt')
    copy_new(ROOT / 'Assets/Branding/AngelLandStoryIcon.png', PLAYER / 'AngelLandStoryIcon.png')
    files = [(name, path, sha(path)) for name, path in shipping.inventory()]
    hashes = {name: digest for name, _, digest in files}
    require(all(hashes.get(name) == digest for name, digest in payload.items()), 'Player changed before packaging.')
    write_new(EVIDENCE / 'shipping-sha256.json', hashes)
    watched = {p: sha(p) for p in (EVIDENCE / 'release-validation.json', EVIDENCE / 'source-continuity.json',
                                  EVIDENCE / 'source-build.json', EVIDENCE / 'ReleaseStartup/report.json', NOTES)}
    print('Packaging the verified local 0.46.8 player...', flush=True)
    with zipfile.ZipFile(pending, 'x', zipfile.ZIP_DEFLATED, compresslevel=5) as packed:
        for name, path, _ in files:
            packed.write(path, name)
    with zipfile.ZipFile(pending) as packed:
        require(set(packed.namelist()) == set(hashes), 'ZIP inventory mismatch.')
        for name, path, digest in files:
            # Reading every member to EOF verifies its ZIP CRC as well as SHA-256.
            with packed.open(name) as stream:
                require(hashlib.file_digest(stream, 'sha256').hexdigest() == digest,
                        'ZIP content hash mismatch: ' + name)
            require(sha(path) == digest, 'Player file changed during packaging: ' + name)
    require({name for name, _ in shipping.inventory()} == set(hashes), 'Player inventory changed.')
    require(all(sha(path) == digest for path, digest in watched.items()), 'Release evidence changed during packaging.')
    require(all(sha(ROOT / name) == digest for name, digest in freeze['sourceFiles'].items()),
            'Product sources changed during packaging.')
    require(sha(PREVIOUS) == PREVIOUS_SHA, 'Previous version package changed.')
    result = {'version': VERSION, 'package': PACKAGE.relative_to(ROOT).as_posix(),
              'sha256': sha(pending), 'bytes': pending.stat().st_size,
              'unpackedBytes': sum(path.stat().st_size for _, path, _ in files),
              'verifiedEntryHashes': len(files), 'fullZipCrcPassed': True,
              'secondSourceHashCheckPassed': True, 'previousReleasePreserved': True,
              'localPackageOnly': True, 'buildUploadAuthorized': False, 'utc': datetime.now(timezone.utc).isoformat()}
    write_new(EVIDENCE / 'package-verification.json', result)
    os.link(pending, PACKAGE)
    pending.unlink()
    with checksum.open('x', encoding='utf-8', newline='\n') as stream:
        stream.write(result['sha256'] + '  ' + PACKAGE.name + '\n')
    print(json.dumps(result, indent=2), flush=True)


if __name__ == '__main__':
    main()
