"""Assemble a self-describing research package archive with a file manifest.

This is NOT the platform's `.science` export (no export operation is exposed to the agent
session). It is a plain ZIP of the research record with SHA-256 hashes, so the investigation
remains inspectable and re-runnable without the application.

Writes: package_manifest.json and ptp1b_research_package.zip in the data directory.
"""
import hashlib, json, zipfile
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
EXCLUDE_DIRS = {"__pycache__", ".ipynb_checkpoints"}
EXCLUDE_FILES = {"ptp1b_research_package.zip", "package_manifest.json", ".DS_Store"}
EXTERNAL = ("independent/", "sources/", "provenance/notebook_replay.json", "provenance/script_replay.json", "provenance/presentation_edits.json",
            "provenance/run_environment.json", "scene/asset_audit.json")
PRESTAGED = ("data/raw/", "provenance/retrieval.json", "provenance/source_selection.md", "research_plan.md", "research_question.md", "analysis/retrieve.py", "scene/vendor/")


def role(rel):
    if rel.startswith(EXTERNAL):
        return "written outside the main research session (local technician / verification process)"
    if rel.startswith(PRESTAGED):
        return "pre-staged input"
    if rel.startswith("scene/"):
        return "3D laboratory deliverable"
    return "research record produced in the main session"


def main():
    files = []
    for p in sorted(ROOT.rglob("*")):
        if not p.is_file() or p.name in EXCLUDE_FILES or any(part in EXCLUDE_DIRS for part in p.parts):
            continue
        rel = p.relative_to(ROOT).as_posix()
        data = p.read_bytes()
        files.append(dict(path=rel, bytes=len(data), sha256=hashlib.sha256(data).hexdigest(), role=role(rel)))
    manifest = dict(
        title="PTP1B Allosteric Discovery — research package",
        created_utc=datetime.now(timezone.utc).isoformat(),
        format="plain ZIP with manifest; not the Open-Science .science export format",
        science_export_status="pending: no export operation was available to the agent session; export from the application",
        entry_points=dict(overview="README.md", question="research_question.md", plan="research_plan.md", results="results/", notebook="research_notebook.ipynb",
                          verification="verification_report.md", limitations="limitations.md", timeline="research_timeline.md",
                          laboratory="scene/ptp1b_research_lab.html"),
        n_files=len(files), total_bytes=sum(f["bytes"] for f in files), files=files)
    (ROOT / "package_manifest.json").write_text(json.dumps(manifest, indent=1))
    out = ROOT / "ptp1b_research_package.zip"
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as z:
        z.write(ROOT / "package_manifest.json", "ptp1b_research_package/package_manifest.json")
        for f in files:
            z.write(ROOT / f["path"], "ptp1b_research_package/" + f["path"])
    by_role = {}
    for f in files:
        by_role[f["role"]] = by_role.get(f["role"], 0) + 1
    print(json.dumps(dict(zip=out.name, zip_bytes=out.stat().st_size, n_files=len(files), by_role=by_role), indent=1))


if __name__ == "__main__":
    main()
