from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest


def test_cli_submit_status_logs_list(monkeypatch, tmp_path: Path, capsys):
    from argus.ray import ray_job_tool as tool_mod

    class _Tool:
        def __init__(self, cfg):
            self.cfg = cfg

        def submit(self, spec, no_wait: bool):
            return "sid1"

        def status(self, sid: str):
            return "RUNNING"

        def stop(self, sid: str):
            return True

        def logs(self, sid: str):
            return "1\n2\n3\n"

        def list(self):
            return [{"a": 1}]

    monkeypatch.setattr(tool_mod, "RayJobTool", _Tool)

    cfg = tmp_path / "cfg.yaml"
    cfg.write_text(
        "ray:\n  address: http://127.0.0.1:8265\n  shared_root: /private\n  entrypoint_resources: {worker_node: 1}\n",
        encoding="utf-8",
    )
    spec = tmp_path / "spec.yaml"
    spec.write_text("workload: ppo\ncode_path: /c\nmodel_id: m\ntrain_file: t\nval_file: v\n", encoding="utf-8")

    from argus.cli.run import main

    monkeypatch.setattr(sys, "argv", ["run.py", "--config", str(cfg), "--taskspec", str(spec), "--action", "submit"])
    assert main() == 0
    assert capsys.readouterr().out.strip() == "sid1"

    monkeypatch.setattr(sys, "argv", ["run.py", "--config", str(cfg), "--action", "status", "--submission-id", "sid1"])
    assert main() == 0
    assert capsys.readouterr().out.strip() == "RUNNING"

    monkeypatch.setattr(
        sys, "argv", ["run.py", "--config", str(cfg), "--action", "logs", "--submission-id", "sid1", "--tail", "1"]
    )
    assert main() == 0
    assert capsys.readouterr().out.strip() == "3"

    monkeypatch.setattr(sys, "argv", ["run.py", "--config", str(cfg), "--action", "list"])
    assert main() == 0
    out = capsys.readouterr().out
    assert json.loads(out)[0]["a"] == 1


def test_cli_requires_submission_id_for_status():
    from argus.cli.run import main

    tmp = Path(__import__("tempfile").gettempdir()) / "mvp_test_cfg.yaml"
    tmp.write_text(
        "ray:\n  address: http://127.0.0.1:8265\n  shared_root: /private\n  entrypoint_resources: {worker_node: 1}\n",
        encoding="utf-8",
    )
    try:
        with pytest.raises(SystemExit):
            sys.argv = ["run.py", "--config", str(tmp), "--action", "status"]
            main()
    finally:
        tmp.unlink(missing_ok=True)
