#!/usr/bin/env python3
"""Collect Suite26's already-saved analysis reports; no training or recomputation.

Usage:
  python3 collect_suite26_review.py --results-dir /path/to/results \
      --output /path/to/suite26_review_reports.zip

The archive contains aggregate reports, fold audits and row-level routing
diagnostics. It excludes predictions, model weights and input caches. Missing
reports are recorded in the manifest, never replaced with synthetic results.
"""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import re
import zipfile

ROOT_NAMES = (
    'per_cell_metrics.csv', 'per_faculty_metrics.csv', 'per_fold_metrics.csv',
    'macro_metrics.csv', 'paired_metrics.csv', 'paired_summary.csv',
    'component_uplifts.csv', 'aligned_cells.csv', 'bootstrap_ap.csv',
    'bootstrap_replicates.csv',
    'thresholds.csv', 'operational_metrics.csv', 'it_confusion.csv',
    'reference_alignment_audit.csv', 'reference_alignment.csv', 'report.json',
    'run_manifest.json', 'manifest.json',
)
FOLD_NAMES = (
    'data_audit.json', 'fold_summary.json', 'training_log.csv',
    'tree_diagnostics.json', 'memory_diagnostics.csv', 'regime_metrics.csv',
    'intervention_metrics.csv', 'intervention_macro_ap.json',
    'history_shuffle_audit.json',
)
REQUIRED_ROOT = (
    'per_cell_metrics.csv', 'per_faculty_metrics.csv', 'macro_metrics.csv',
    'paired_metrics.csv', 'bootstrap_ap.csv', 'operational_metrics.csv',
)


def collect(results_dir: Path, output: Path) -> dict:
    root = results_dir.expanduser().resolve()
    output = output.expanduser().resolve()
    if not root.is_dir():
        raise ValueError(f'Results directory not found: {root}')
    if output.exists():
        raise ValueError(f'Output already exists; choose a new filename: {output}')
    selected = []
    missing = [name for name in REQUIRED_ROOT if not (root / name).is_file()]
    for name in ROOT_NAMES:
        if (root / name).is_file():
            selected.append(root / name)
    folds = sorted(
        (p for p in root.iterdir() if p.is_dir() and re.fullmatch(r'fold_\d+', p.name)),
        key=lambda p: int(p.name.split('_')[-1]),
    )
    for fold in folds:
        for name in FOLD_NAMES:
            path = fold / name
            if path.is_file():
                selected.append(path)
            else:
                missing.append(str(path.relative_to(root)))
    if not selected:
        raise ValueError(f'No recognized Suite26 reports in {root}')
    manifest = {
        'format_version': 1,
        'operation': 'archive_existing_reports_without_recomputation',
        'results_dir': str(root),
        'fold_directories': [p.name for p in folds],
        'missing_reports': missing,
        'excluded': ['prediction tables', 'model weights', 'input caches'],
        'files': [],
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    created = False
    try:
        with output.open('xb') as destination:
            created = True
            with zipfile.ZipFile(destination, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
                for path in selected:
                    relative = path.relative_to(root).as_posix()
                    payload = path.read_bytes()
                    archive.writestr(relative, payload)
                    manifest['files'].append({
                        'path': relative, 'bytes': len(payload),
                        'sha256': hashlib.sha256(payload).hexdigest(),
                    })
                archive.writestr('review_collection_manifest.json',
                                 json.dumps(manifest, indent=2) + '\n')
    except Exception:
        if created:
            output.unlink(missing_ok=True)
        raise
    return manifest


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--results-dir', type=Path, default=Path(
        '/root/disk_3tb/earlywarning/30072026/results/suite26_joint_tree_memory'))
    parser.add_argument('--output', type=Path, default=Path('suite26_review_reports.zip'))
    args = parser.parse_args()
    try:
        manifest = collect(args.results_dir, args.output)
    except (ValueError, OSError, zipfile.BadZipFile) as exc:
        parser.exit(1, f'Collection failed: {exc}\n')
    print(f'Created {args.output.expanduser().resolve()}')
    print(f'Collected {len(manifest["files"])} existing reports from '
          f'{len(manifest["fold_directories"])} folds; no experiment rerun.')
    if manifest['missing_reports']:
        print('Missing reports (also recorded in archive manifest):')
        for name in manifest['missing_reports']:
            print(f'  {name}')


if __name__ == '__main__':
    main()
