from pathlib import Path
import json,hashlib,zipfile,shutil,sys
R=Path(__file__).resolve().parent.parent; W=R.parent
sources={
 'File52c_latest.md':W/'upload/File_52c.Rounded_Whole_Span_Inverse_Detailed_Study_Draft (2)(1).md',
 'File51a.md':W/'project_sources/39-File_51a.Rounded_Scaffold_Mod5_Architecture.md',
 'File18.md':W/'project_sources/38-File_18.Chronological_Data_Tables-20260919-141048-.md',
 'File22.md':W/'project_sources/15-File_22.Cumulative_MT_Harmonics-20260906-202427-.md',
 'Strategy.md':W/'upload/490d_Unification_Research_Strategy_v0_2_20260906.md',
 'C481_report.md':W/'490d_C481_Shared_12026_Anchor_and_529_Grammar_20260927.md',
 'C481_checkpoint.md':W/'490d_Mirror_Rounded_Checkpoint_After_C481_20260927.md',
 'C480_checkpoint.md':W/'c481/evidence/sources/C480_checkpoint.md',
 'Chronology_Three_Axis_Mirrors.png':W/'upload/Chronology_Three_Axis_Mirrors.png'}
for name,p in sources.items():
 dest=R/'evidence/sources'/name
 if not dest.exists():shutil.copyfile(p,dest)
manifest={name:hashlib.sha256((R/'evidence/sources'/name).read_bytes()).hexdigest() for name in sources}
(R/'evidence/SOURCE_MANIFEST.json').write_text(json.dumps(manifest,indent=2)+'\n')
rows=json.loads((R/'journal.json').read_text());last=rows[-1]['step'];first=int(sys.argv[1]) if len(sys.argv)>1 else 482
out=W/f'490d_C{first}_C{last}_Research_20260927.md'
lines=[f'# 490d — C{first}–C{last}: sequential research record','',
 '27 September 2026. Working continuation of C481. File52c’s latest supplied draft controls the rounded investigation. No canonical sources are changed. Second-order inversion remains deferred.','',
 'Each numbered entry records its question, declared inputs, exact results, finding, and reassessment. These are bounded research actions, not claims of independent discoveries. Parallel agents supplied source extraction and critical review; the main sequence was evaluated in order.','']
for x in rows:
 if x['step']<first:continue
 lines += [f"## C{x['step']} — {x['title']}",'',f"**Question.** {x['question']}",'',f"**Source basis.** {'; '.join(x['sources'])}",'','**Frozen inputs**','', '```json',json.dumps(x['inputs'],indent=2,ensure_ascii=False),'```','','**Results**','','```json',json.dumps(x['results'],indent=2,ensure_ascii=False),'```','',f"**Finding.** {x['finding']}",'',f"**Reassessment.** {x['reassessment']}",'']
lines+=['## Evidence','',f"The accompanying evidence checkpoint contains the sequential journal, exact-arithmetic step scripts, source snapshots and SHA256 manifest. Latest step: C{last}. Assertions verify arithmetic or explicit scope decisions; they are not independent historical or statistical witnesses.",'']
out.write_text('\n'.join(lines));shutil.copyfile(out,R/out.name)
payloads=[p for p in R.rglob('*') if p.is_file() and '__pycache__' not in p.parts and p.name!='MANIFEST.sha256']
(R/'MANIFEST.sha256').write_text(''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()}  {p.relative_to(R)}\n' for p in sorted(payloads)))
z=W/f'490d_Evidence_Through_C{last}_20260927.zip'
with zipfile.ZipFile(z,'w',zipfile.ZIP_DEFLATED) as f:
 for p in sorted(R.rglob('*')):
  if p.is_file() and '__pycache__' not in p.parts:f.write(p,str(p.relative_to(R)))
print(json.dumps({'report':str(out),'evidence':str(z),'completed_steps':len(rows),'last_step':last,'zip_sha256':hashlib.sha256(z.read_bytes()).hexdigest()}))
