"""CLI adapter for the worker audit-sidecar contract (`okstra worker-audit-check`).

Phase 7 runs the same rules through `validate-run.py`, but by then the worker
session is gone and the only remedies left are a retroactive edit — which breaks
the audit chain — or a failed run. Called the moment a worker returns, the same
rules cost one message to a worker that is still listening.
"""
from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

from okstra_ctl.worker_audit_ledger import (
    check_worker_results_audit,
    worker_result_files,
)


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="okstra worker-audit-check",
        description="Check one run's worker audit sidecars (read-only).",
    )
    parser.add_argument("--run-dir", type=Path, required=True,
                        help="runs/<task-type>/ for this run")
    parser.add_argument("--task-type", required=True)
    parser.add_argument("--seq", required=True,
                        help="this run's 3-digit seq")
    parser.add_argument("--worker", default=None,
                        help="check only this worker id, with or without the "
                             "`-worker` suffix (default: every worker)")
    return parser


def main(argv: list[str] | None = None) -> int:
    args = _parser().parse_args(argv)
    failures = check_worker_results_audit(
        args.run_dir, args.task_type, args.seq, worker=args.worker
    )
    # A selector that narrows to nothing also produces no failures, so `ok`
    # alone cannot tell a real pass from a check that judged zero files —
    # a mistyped `--worker` used to read as a clean bill of health. The count
    # is what makes the two distinguishable at a glance.
    inspected = [
        path.name
        for path, _role, _seq in worker_result_files(
            args.run_dir, args.task_type, args.seq, args.worker
        )
    ]
    print(json.dumps(
        {
            "ok": not failures,
            "inspected": len(inspected),
            "inspectedFiles": inspected,
            "failures": failures,
        },
        ensure_ascii=False,
        indent=2,
    ))
    return 2 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
