"""Validate and package only the explicitly shareable incident evidence."""
import hashlib
import json
import os
import re
import zipfile
from datetime import datetime, timedelta, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
SHARED = ROOT / 'shared'
os.umask(0o077)
NAMES = ('00_REPORT_ko.md', 'evidence_summary.json', 'preservation_index.json')


def file_info(path, relative_to):
    h = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(block)
    return {'path': str(path.relative_to(relative_to)), 'bytes': path.stat().st_size, 'sha256': h.hexdigest()}


def save(path, value):
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')


for name in NAMES:
    text = (SHARED / name).read_text(encoding='utf-8')
    if any(term in text for term in ('192.168.30.', '58.233.207.', 'rnd@', 'testpc\\rnd', 'C:\\Users\\rnd',
                                     'BEGIN OPENSSH PRIVATE KEY', 'BEGIN RSA PRIVATE KEY')):
        raise RuntimeError('Sensitive literal in shareable output: ' + name)
    if re.search(r'(?i)\b(?:wss?|rtsps?)://|Bearer\s+[A-Za-z0-9._-]+', text):
        raise RuntimeError('Unmasked connection or bearer value: ' + name)
    if name.endswith('.json'):
        json.loads(text)

report = (SHARED / '00_REPORT_ko.md').read_text(encoding='utf-8')
for target in re.findall(r'\]\(([^)]+)\)', report):
    if not target.startswith('https://'):
        assert (SHARED / target).is_file(), target

for source in (ROOT / 'helpers').glob('*.py'):
    compile(source.read_text(encoding='utf-8'), str(source), 'exec')

summary = json.loads((SHARED / 'evidence_summary.json').read_text(encoding='utf-8'))
assert all(summary['checks'].values())
assert len(summary['crashes']) == 2 and len(summary['preserved_dumps']) == 2
assert summary['excerpts'][2]['line'].startswith('2026-10-31T14:36:')

files = [file_info(SHARED / name, SHARED) for name in NAMES]
save(SHARED / 'manifest.json', {
    'schema_version': 'codex.artifact-manifest.v1',
    'created_at': datetime.now(timezone(timedelta(hours=9))).isoformat(),
    'profile': 'ltb1021', 'project': 'contextra', 'task': 'web-media-readonly-analysis',
    'run_id': 'r01', 'lifecycle': 'durable-large', 'cleanup_candidate_at': 'manual-review',
    'contains_raw_memory_or_credentials': False, 'files': files,
})
bundle = ROOT / 'Icerti_Web_Media_Analysis_20261101.zip'
if bundle.exists():
    raise RuntimeError('Published bundle exists; do not replace it.')
with zipfile.ZipFile(bundle, 'x', compression=zipfile.ZIP_DEFLATED) as archive:
    for name in (*NAMES, 'manifest.json'):
        archive.write(SHARED / name, arcname='Icerti_Web_Media_Analysis_20261101/' + name)
with zipfile.ZipFile(bundle) as archive:
    assert archive.testzip() is None
    assert len(archive.infolist()) == 4
    for info in archive.infolist():
        name = Path(info.filename).name
        assert archive.read(info) == (SHARED / name).read_bytes()

save(ROOT / 'manifest.json', {
    'schema_version': 'codex.artifact-manifest.v1',
    'created_at': datetime.now(timezone(timedelta(hours=9))).isoformat(),
    'profile': 'ltb1021', 'project': 'contextra', 'task': 'web-media-readonly-analysis',
    'run_id': 'r01', 'lifecycle': 'durable-large', 'cleanup_candidate_at': 'manual-review',
    'private_evidence_not_for_redistribution': True,
    'files': [file_info(path, ROOT) for path in sorted(ROOT.rglob('*')) if path.is_file()
              and path != ROOT / 'manifest.json'],
})
print(json.dumps({'bundle': str(bundle), 'bundle_sha256': file_info(bundle, ROOT)['sha256'],
                  'share_files': 4, 'runtime_checks_passed': len(summary['checks']),
                  'archive_and_links_verified': True}, ensure_ascii=False))
