"""Build a deterministic installable candidate, excluding developer/test files."""
import hashlib
import json
import re
import sys
import zipfile
from pathlib import Path

root = Path(__file__).resolve().parent.parent
if len(sys.argv) != 2:
    raise SystemExit('Usage: python3 scripts/package-release.py OUTPUT_DIRECTORY')
output = Path(sys.argv[1]).resolve()
output.mkdir(parents=True, exist_ok=True)
version = re.search(r'\* Version:\s+(\S+)', (root / 'netpay-checkout.php').read_text()).group(1)
files = [root / name for name in ('netpay-checkout.php', 'netpay-util.php', 'index.php', 'LICENSE', 'README.md', 'readme.txt', 'CHANGELOG.md')]
for folder in ('includes', 'assets', 'templates', 'languages'):
    files.extend(p for p in (root / folder).rglob('*') if p.is_file() and not any(part.startswith('.') for part in p.relative_to(root).parts))
files = sorted(set(files))
archive = output / f'netpay-checkout-{version}-candidate.zip'
manifest = []
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as package:
    for source in files:
        if source.is_symlink():
            raise RuntimeError(f'Symlink is not allowed: {source}')
        relative = source.relative_to(root).as_posix()
        data = source.read_bytes()
        entry = zipfile.ZipInfo('netpay-checkout/' + relative, (1980, 1, 1, 0, 0, 0))
        entry.compress_type = zipfile.ZIP_DEFLATED
        entry.external_attr = 0o100644 << 16
        package.writestr(entry, data)
        manifest.append({'file': relative, 'sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data)})
checksum = hashlib.sha256(archive.read_bytes()).hexdigest()
with zipfile.ZipFile(archive) as package:
    assert package.testzip() is None
    for entry in package.namelist():
        assert entry.startswith('netpay-checkout/') and '..' not in Path(entry).parts
    for required in ('class-netpay-installment-policy.php', 'class-netpay-notifications.php', 'class-netpay-order-actions.php'):
        assert 'netpay-checkout/includes/' + required in package.namelist()
(output / (archive.name + '.sha256')).write_text(checksum + '  ' + archive.name + '\n')
(output / 'candidate-manifest.json').write_text(json.dumps({'version': version, 'status': 'candidate for QA; transaction refunds/cancellations only in NetPay Manager', 'archive': archive.name, 'sha256': checksum, 'files': manifest}, indent=2) + '\n')
print(json.dumps({'archive': str(archive), 'sha256': checksum, 'files': len(files), 'bytes': archive.stat().st_size}))
