#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Operator CLI for the Phase 5 run entry point.

    orchestrate.py start   --spec RUN_SPEC.yaml --workdir DIR --store STORE.db
    orchestrate.py inspect --run-id RUN_ID --store STORE.db
    orchestrate.py stop    --run-id RUN_ID --store STORE.db

``start`` freezes the target described by the run-spec, admits the run, and
drives the root's execute to an evidence-bound acceptance claim or a recorded
refusal. ``inspect`` prints the stored run read-only. ``stop`` settles live
attempts and admits the run's cancellation. The CLI imports no experiment-harness
module; the run-spec format is documented in ``docs/run-entry.md``.
"""

from __future__ import annotations

import argparse
import dataclasses
import json
import os
import sys
from typing import Optional, Sequence

REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(REPO_ROOT, "src"))

from orchestrator import run_entry  # noqa: E402
from orchestrator.sandbox import SandboxLimits  # noqa: E402
from orchestrator.store import EventStore  # noqa: E402


def _print(document) -> None:
    sys.stdout.write(json.dumps(document, indent=2, sort_keys=True, default=str) + "\n")


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="orchestrate",
        description="Start, inspect, and stop an orchestrator run from a run-spec.",
    )
    commands = parser.add_subparsers(dest="command", required=True)

    start = commands.add_parser("start", help="freeze a target and run one root execute")
    start.add_argument("--spec", required=True, help="path to the run-spec YAML document")
    start.add_argument("--workdir", required=True, help="scratch directory for worktrees and artefacts")
    start.add_argument("--store", required=True, help="path to the event store")
    start.add_argument(
        "--sandbox-wall-seconds",
        type=float,
        default=None,
        help="override the sandbox wall-clock bound for this run",
    )

    inspect = commands.add_parser("inspect", help="print a stored run read-only")
    inspect.add_argument("--run-id", required=True)
    inspect.add_argument("--store", required=True)

    stop = commands.add_parser("stop", help="cancel a run and settle its live attempts")
    stop.add_argument("--run-id", required=True)
    stop.add_argument("--store", required=True)
    return parser


def main(argv: Optional[Sequence[str]] = None) -> int:
    args = _build_parser().parse_args(argv)

    if args.command == "start":
        spec = run_entry.load_run_spec(args.spec)
        limits = (
            SandboxLimits(wall_seconds=args.sandbox_wall_seconds)
            if args.sandbox_wall_seconds is not None
            else None
        )
        store = EventStore(os.path.abspath(args.store))
        try:
            result = run_entry.start_run(
                spec,
                store=store,
                workdir=os.path.abspath(args.workdir),
                sandbox_limits=limits,
            )
        finally:
            store.close()
        _print(dataclasses.asdict(result))
        return 0 if result.accepted else 1

    if args.command == "inspect":
        store = EventStore(os.path.abspath(args.store))
        try:
            document = run_entry.inspect_run(store, args.run_id)
        finally:
            store.close()
        _print(document)
        return 0

    store = EventStore(os.path.abspath(args.store))
    try:
        outcome = run_entry.stop_run(store, args.run_id)
    finally:
        store.close()
    _print({"run_id": args.run_id, "outcome": outcome})
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
