#!/usr/bin/env python3
"""Build code-only source and compact handover archives after release gates pass."""
import hashlib
import os
from pathlib import Path
import shutil
import sys
import zipfile

root = Path(__file__).resolve().parents[1]
destination = Path(sys.argv[1]).resolve()
handover = Path(sys.argv[2]).resolve()
destination.mkdir(parents=True, exist_ok=True)
handover.mkdir(parents=True, exist_ok=True)

# Refresh prior selected handover files and add the preserved report sources.
for target in list(handover.rglob('*')):
    source = root / target.relative_to(handover)
    if target.is_file() and source.is_file():
        shutil.copy2(source, target)
for relative in ['app/Services/Reports', 'app/Support/Reporting', 'app/Http/Requests/Reports',
                 'app/Console/Commands', 'database/migrations', 'database/sql', 'docs/reporting',
                 'resources/views/analysis', 'tests', 'deployment', 'load-tests', 'powerbi', 'scripts']:
    shutil.copytree(root / relative, handover / relative, dirs_exist_ok=True,
                    ignore=shutil.ignore_patterns('__pycache__', '*.pyc'))
for relative in ['app/Http/Controllers/LegacyPivotReportingController.php',
                 'public/assets/js/ngbvd-report-workbench.js', 'public/assets/js/ngbvd-pivot-dataset-worker.js',
                 'public/assets/css/ngbvd-roles-analysis.css', 'public/pivotjs/pivot.js',
                 'README_REPORTING_IMPLEMENTATION.md']:
    target = handover / relative
    target.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(root / relative, target)


def build_archive(base, target, source_archive=False):
    temporary = target.with_suffix('.building.zip')
    with zipfile.ZipFile(temporary, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
        for current, directories, filenames in os.walk(base):
            directories[:] = sorted(directory for directory in directories if directory not in
                                     {'node_modules', '.git', '__pycache__'})
            relative_directory = Path(current).relative_to(base)
            if relative_directory != Path('.'):
                archive.writestr(relative_directory.as_posix() + '/', '')
            for filename in sorted(filenames):
                relative = relative_directory / filename
                name = relative.as_posix()
                if filename.endswith('.pyc') or (filename.startswith('.env') and not filename.endswith('.example')):
                    continue
                if source_archive and ((name.startswith('bootstrap/cache/') and filename.endswith('.php'))
                                       or (name.startswith(('storage/logs/', 'storage/framework/', 'storage/app/private/'))
                                           and filename != '.gitignore')):
                    continue
                source = base / relative
                if source.is_symlink():
                    raise RuntimeError('Unexpected symlink in release tree: ' + name)
                archive.write(source, name)
    with zipfile.ZipFile(temporary) as archive:
        corrupt = archive.testzip()
        if corrupt:
            raise RuntimeError('ZIP integrity failure: ' + corrupt)
        names = set(archive.namelist())
        required = {'app/Services/Reports/LegacyPivotReportingService.php',
                    'app/Console/Commands/ReportingStatus.php', 'app/Support/Reporting/ReportingSnapshotReadiness.php',
                    'scripts/initialize_ngbvd_reporting.ps1', 'docs/reporting/REPORTS_503_RECOVERY.md',
                    'public/assets/js/ngbvd-report-workbench.js', 'public/assets/js/ngbvd-pivot-dataset-worker.js',
                    'resources/views/analysis/standard_workbench.blade.php',
                    'docs/reporting/PRESERVED_REPORTS_PERFORMANCE.md', 'tests/js/preserved_reports.test.js'}
        if not required.issubset(names):
            raise RuntimeError('Missing preserved report release files')
        if source_archive and ('vendor/autoload.php' not in names or 'artisan' not in names):
            raise RuntimeError('Missing application dependencies/bootstrap')
        if any('/node_modules/' in '/' + name or name in {'.env', 'bootstrap/cache/config.php',
                   'bootstrap/cache/packages.php', 'bootstrap/cache/services.php'} for name in names):
            raise RuntimeError('Unexpected deployment cache/secret/dependency directory in release')
    os.replace(temporary, target)
    return len(names)


artifacts = [('NGBVD_Reporting_Updated_Source_20261009.zip', root, True),
             ('NGBVD_Reporting_Handover_20261009.zip', handover, False)]
lines = []
for filename, base, is_source in artifacts:
    target = destination / filename
    count = build_archive(base, target, is_source)
    digest = hashlib.file_digest(target.open('rb'), 'sha256').hexdigest()
    lines.append(digest + '  ' + filename)
    print(filename + ': ' + str(target.stat().st_size) + ' bytes, ' + str(count) + ' entries, ZIP CRC passed', flush=True)

# Small overlay for a deployment already on the preserved-report release.
overlay_files = [
    'app/Console/Commands/ReportingStatus.php', 'app/Support/Reporting/ReportingSnapshotReadiness.php',
    'app/Exceptions/StaleReportingSnapshotException.php', 'app/Services/Reports/IncidentReportingService.php',
    'app/Services/Reports/LegacyPivotReportingService.php', 'app/Services/Reports/ReportingSnapshotRefresher.php',
    'app/Http/Controllers/LegacyPivotReportingController.php', 'app/Http/Middleware/ReportTiming.php',
    'public/assets/js/ngbvd-report-workbench.js', 'resources/views/analysis/standard_workbench.blade.php',
    'scripts/initialize_ngbvd_reporting.ps1', 'docs/reporting/REPORTS_503_RECOVERY.md',
    'docs/reporting/PRESERVED_REPORTS_PERFORMANCE.md', 'docs/reporting/CHANGE_MANIFEST.md',
    'docs/reporting/VALIDATION_REPORT.md', 'docs/reporting/MONITORING_GUIDE.md', 'docs/reporting/HANDOVER_INDEX.md',
    'README_REPORTING_IMPLEMENTATION.md', 'tests/Unit/ReportingSnapshotReadinessTest.php',
    'tests/js/preserved_reports.test.js',
]
overlay_name = 'NGBVD_Reporting_503_Fix_20261010.zip'
overlay_target = destination / overlay_name
overlay_temporary = overlay_target.with_suffix('.building.zip')
with zipfile.ZipFile(overlay_temporary, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
    for relative in overlay_files:
        archive.write(root / relative, relative)
with zipfile.ZipFile(overlay_temporary) as archive:
    assert archive.testzip() is None
    assert set(archive.namelist()) == set(overlay_files)
os.replace(overlay_temporary, overlay_target)
lines.append(hashlib.file_digest(overlay_target.open('rb'), 'sha256').hexdigest() + '  ' + overlay_name)
print(overlay_name + ': ' + str(overlay_target.stat().st_size) + ' bytes, ' + str(len(overlay_files)) + ' entries, ZIP CRC passed', flush=True)
(destination / 'NGBVD_Reporting_SHA256SUMS_20261009.txt').write_text('\n'.join(lines) + '\n')
print('Source, handover, 503 repair overlay and checksum manifest rebuilt.', flush=True)
