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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/env python3
"""Materialize auditable HiQBind Protenix poses for pooled-v2 construction.

This program is intentionally independent of Docking Base's generic
``materialize_hiqbind_gnncp.py``.  It has the same non-destructive materialization
model (validate published common output, then hard-link into a new flat tree),
but makes one Protenix policy explicit:

* ``success`` and ``partial`` result manifests are eligible by default;
* a ``failed`` result is eligible *only* when ``--include-failed-with-poses`` is
  supplied and its published ``poses.csv`` points to one or more real PDB files.

The latter is needed for Protenix's protein-alignment quality gate: some
terminal ``failed`` manifests deliberately retain chemically valid ligand poses.
Those poses must never be silently mixed into an all-success dataset.  Each
materialized record therefore retains the source result status and provenance in
``source_index.json``.

The script never modifies its source roots and refuses to reuse an output path.
It writes only to a private staging directory under the requested output parent,
then atomically publishes the completed directory.
"""

from __future__ import annotations

import argparse
import csv
import json
import os
import re
import shutil
import sys
import tempfile
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Mapping


TARGET_RE = re.compile(r"[A-Za-z0-9_.-]+\Z")
NORMAL_STATUSES = frozenset({"success", "partial"})
FAILED_STATUS = "failed"


class MaterializeError(RuntimeError):
    """A source/output safety or eligibility error."""


def _utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


def _read_json(path: Path) -> dict[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise MaterializeError(f"cannot read JSON {path}: {exc}") from exc
    if not isinstance(value, dict):
        raise MaterializeError(f"JSON object expected in {path}")
    return value


def _write_json(path: Path, value: Mapping[str, Any]) -> None:
    """Write a small metadata file inside the not-yet-published staging tree."""
    path.write_text(
        json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n",
        encoding="utf-8",
    )


def _inside(path: Path, root: Path) -> Path:
    """Resolve a source reference and ensure it cannot escape its native directory."""
    resolved = path.resolve()
    try:
        resolved.relative_to(root.resolve())
    except ValueError as exc:
        raise MaterializeError(f"path escapes published native output: {path}") from exc
    return resolved


def _pose_rows(native: Path) -> list[dict[str, Any]]:
    """Read usable published PDB poses in deterministic rank/name order."""
    csv_path = native / "poses.csv"
    try:
        with csv_path.open("r", newline="", encoding="utf-8") as handle:
            raw_rows = list(csv.DictReader(handle))
    except OSError as exc:
        raise MaterializeError(f"cannot read {csv_path}: {exc}") from exc
    if not raw_rows:
        raise MaterializeError(f"no emitted poses in {csv_path}")

    rows: list[dict[str, Any]] = []
    seen_paths: set[Path] = set()
    for ordinal, row in enumerate(raw_rows, start=1):
        raw_path = row.get("pose_file")
        if not raw_path:
            raise MaterializeError(f"{csv_path}: pose row {ordinal} has no pose_file")
        candidate = Path(raw_path)
        source = candidate if candidate.is_absolute() else native / candidate
        source = _inside(source, native)
        if source.suffix.lower() != ".pdb" or not source.is_file():
            raise MaterializeError(
                f"{csv_path}: unsupported or missing PDB pose {source}"
            )
        if source in seen_paths:
            raise MaterializeError(f"{csv_path}: duplicate pose file {source}")
        seen_paths.add(source)
        rank_text = row.get("rank", "")
        try:
            rank = int(rank_text)
        except ValueError:
            rank = ordinal
        rows.append(
            {
                "rank": rank,
                "row_ordinal": ordinal,
                "source": source,
                "source_relative_path": str(source.relative_to(native.resolve())),
                "pose_id": row.get("pose_id", ""),
                "score": row.get("score", ""),
                "score_type": row.get("score_type", ""),
                "seed": row.get("seed", ""),
                "sample": row.get("sample", ""),
            }
        )
    rows.sort(key=lambda item: (int(item["rank"]), str(item["source"].name)))
    return rows


def _source_patterns() -> tuple[str, ...]:
    """Published output layouts produced by the HiQBind launchers."""
    return (
        "output/protenix/*/native/manifest.json",
        "shards/*/protenix/output/protenix/*/native/manifest.json",
        "workers/*/units/*/protenix/output/protenix/*/native/manifest.json",
        "*/protenix/output/protenix/*/native/manifest.json",
    )


def _is_eligible(status: str, include_failed_with_poses: bool) -> bool:
    return status in NORMAL_STATUSES or (
        include_failed_with_poses and status == FAILED_STATUS
    )


def _discover(
    source_roots: Iterable[Path],
    *,
    include_failed_with_poses: bool,
) -> dict[str, dict[str, Any]]:
    """Discover eligible published targets; later roots take target precedence."""
    selected: dict[str, dict[str, Any]] = {}
    for source_root in source_roots:
        if not source_root.is_dir():
            raise MaterializeError(f"source root is not a directory: {source_root}")
        manifest_paths = {
            path
            for pattern in _source_patterns()
            for path in source_root.glob(pattern)
        }
        for manifest_path in sorted(manifest_paths, key=lambda value: str(value)):
            native = manifest_path.parent.resolve()
            target = native.parent.name
            if not TARGET_RE.fullmatch(target):
                raise MaterializeError(f"unsafe target name {target!r} in {native}")
            manifest = _read_json(manifest_path)
            status = manifest.get("status")
            if not isinstance(status, str) or not _is_eligible(
                status, include_failed_with_poses
            ):
                continue
            if status == FAILED_STATUS:
                # A terminal failure is eligible only when its *published*
                # pose table really resolves to usable PDB files.  Do this
                # before it is allowed to take precedence over an earlier
                # source root for the same target.
                try:
                    if not _pose_rows(native):
                        continue
                except MaterializeError:
                    continue
            selected[target] = {
                "native": native,
                "manifest_path": manifest_path.resolve(),
                "manifest": manifest,
                "source_root": source_root.resolve(),
                "status": status,
            }
    return selected


def _link(source: Path, destination: Path) -> None:
    if destination.exists() or destination.is_symlink():
        raise MaterializeError(f"unexpected existing materialized file: {destination}")
    try:
        os.link(source, destination)
    except OSError as exc:
        raise MaterializeError(
            "hard-link failed "
            f"({source} -> {destination}); source and output must share a filesystem: {exc}"
        ) from exc


def _check_output_is_safe(output_root: Path, source_roots: Iterable[Path]) -> None:
    if output_root.exists() or output_root.is_symlink():
        raise MaterializeError(f"output root already exists; refusing to replace it: {output_root}")
    for source_root in source_roots:
        try:
            output_root.relative_to(source_root)
        except ValueError:
            continue
        raise MaterializeError(
            f"output root must not be inside source root: {output_root} inside {source_root}"
        )


def _materialize_record(
    *,
    target: str,
    source: Mapping[str, Any],
    staging: Path,
    max_poses: int,
    include_failed_with_poses: bool,
) -> dict[str, Any]:
    native = Path(source["native"])
    status = str(source["status"])
    protein = _inside(native / "protein.pdb", native)
    ligand = _inside(native / "ligand.pdb", native)
    if not protein.is_file() or not ligand.is_file():
        raise MaterializeError("missing protein.pdb or ligand.pdb")

    rows = _pose_rows(native)
    if status == FAILED_STATUS and not include_failed_with_poses:
        # Defensive redundancy: _discover already rejects this case.
        raise MaterializeError("failed result requires --include-failed-with-poses")
    if not rows:
        raise MaterializeError("no usable PDB poses")
    rows = rows[:max_poses]

    destination = staging / target
    destination.mkdir()
    try:
        _link(protein, destination / "protein.pdb")
        _link(ligand, destination / "ligand.pdb")
        materialized_names: list[str] = []
        pose_provenance: list[dict[str, Any]] = []
        for ordinal, row in enumerate(rows, start=1):
            name = f"{target}_pose_{ordinal:03d}.pdb"
            _link(Path(row["source"]), destination / name)
            materialized_names.append(name)
            pose_provenance.append(
                {
                    "materialized_name": name,
                    "source_relative_path": row["source_relative_path"],
                    "source_rank": int(row["rank"]),
                    "source_row_ordinal": int(row["row_ordinal"]),
                    "source_pose_id": row["pose_id"],
                    "score": row["score"],
                    "score_type": row["score_type"],
                    "seed": row["seed"],
                    "sample": row["sample"],
                }
            )
    except Exception:
        shutil.rmtree(destination, ignore_errors=True)
        raise

    manifest = source["manifest"]
    return {
        "source_root": str(source["source_root"]),
        "source_native": str(native),
        "source_manifest": str(source["manifest_path"]),
        "source_result_status": status,
        "source_emitted_pose_count": manifest.get("emitted_pose_count"),
        "accepted_by_policy": (
            "success_or_partial"
            if status in NORMAL_STATUSES
            else "failed_with_published_poses_explicitly_included"
        ),
        "pose_count": len(materialized_names),
        "materialized_poses": materialized_names,
        "pose_provenance": pose_provenance,
    }


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--source-root",
        action="append",
        type=Path,
        required=True,
        help="published HiQBind run root; repeatable, later roots take precedence",
    )
    parser.add_argument("--output-root", type=Path, required=True)
    parser.add_argument(
        "--include-failed-with-poses",
        action="store_true",
        help=(
            "explicitly include only failed manifests whose published poses.csv "
            "contains usable PDB poses; source_result_status remains failed in metadata"
        ),
    )
    parser.add_argument(
        "--target",
        action="append",
        default=[],
        help="repeatable exact target filter (useful for a smoke materialization)",
    )
    parser.add_argument("--max-systems", type=int)
    parser.add_argument("--max-poses-per-system", type=int, default=20)
    return parser


def main(argv: list[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    if args.max_systems is not None and args.max_systems <= 0:
        raise MaterializeError("--max-systems must be positive")
    if args.max_poses_per_system <= 0:
        raise MaterializeError("--max-poses-per-system must be positive")

    source_roots = [path.expanduser().resolve() for path in args.source_root]
    output_root = args.output_root.expanduser().resolve()
    _check_output_is_safe(output_root, source_roots)
    selected = _discover(
        source_roots,
        include_failed_with_poses=bool(args.include_failed_with_poses),
    )
    requested_targets = set(args.target)
    if requested_targets:
        selected = {key: value for key, value in selected.items() if key in requested_targets}
        absent = sorted(requested_targets.difference(selected), key=str.casefold)
        if absent:
            raise MaterializeError(
                "requested targets were not eligible/published: " + ", ".join(absent)
            )
    ordered_targets = sorted(selected, key=str.casefold)
    if args.max_systems is not None:
        ordered_targets = ordered_targets[: args.max_systems]
    if not ordered_targets:
        raise MaterializeError("no eligible Protenix systems discovered")

    output_root.parent.mkdir(parents=True, exist_ok=True)
    staging = Path(
        tempfile.mkdtemp(prefix=f".{output_root.name}.building-", dir=output_root.parent)
    )
    records: dict[str, Any] = {}
    skipped: dict[str, str] = {}
    try:
        for target in ordered_targets:
            source = selected[target]
            try:
                records[target] = _materialize_record(
                    target=target,
                    source=source,
                    staging=staging,
                    max_poses=int(args.max_poses_per_system),
                    include_failed_with_poses=bool(args.include_failed_with_poses),
                )
            except MaterializeError as exc:
                shutil.rmtree(staging / target, ignore_errors=True)
                skipped[target] = str(exc)

        if not records:
            raise MaterializeError("all selected Protenix systems were unusable")
        status_counts = Counter(
            record["source_result_status"] for record in records.values()
        )
        source_index: dict[str, Any] = {
            "kind": "hiqbind_protenix_usable_pose_materialization_v2",
            "method": "protenix",
            "policy": {
                "normal_eligible_statuses": sorted(NORMAL_STATUSES),
                "include_failed_with_poses": bool(args.include_failed_with_poses),
                "failed_inclusion_rule": (
                    "only a failed manifest with a non-empty poses.csv whose every "
                    "selected pose resolves to an existing PDB within the native output"
                ),
            },
            "records": records,
            "skipped": skipped,
        }
        _write_json(staging / "source_index.json", source_index)
        _write_json(
            staging / "materialization_manifest.json",
            {
                "kind": "hiqbind_protenix_usable_pose_materialization_v2",
                "created_utc": _utc_now(),
                "method": "protenix",
                "link_mode": "hardlink",
                "source_roots": [str(path) for path in source_roots],
                "requested_system_count": len(ordered_targets),
                "materialized_system_count": len(records),
                "materialized_pose_count": sum(
                    int(record["pose_count"]) for record in records.values()
                ),
                "materialized_systems_by_source_status": dict(sorted(status_counts.items())),
                "skipped_system_count": len(skipped),
                "max_poses_per_system": int(args.max_poses_per_system),
                "include_failed_with_poses": bool(args.include_failed_with_poses),
                "target_filter": sorted(requested_targets, key=str.casefold),
            },
        )
        os.replace(staging, output_root)
    except Exception:
        shutil.rmtree(staging, ignore_errors=True)
        raise

    result = {
        "output_root": str(output_root),
        **_read_json(output_root / "materialization_manifest.json"),
    }
    print(json.dumps(result, sort_keys=True))
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except MaterializeError as exc:
        print(f"error: {exc}", file=sys.stderr)
        raise SystemExit(2)