import subprocess
from pathlib import Path

import pytest

import claudex
from test_claudex import _fake_claude_account


def test_validate_seat_resume_argv_accepts_explicit_ids() -> None:
    claudex.validate_seat_resume_argv(["resume", "sid-1"])
    claudex.validate_seat_resume_argv(["--resume", "sid-2"])


@pytest.mark.parametrize(
    "argv",
    [
        ["--continue"],
        ["-c"],
        ["resume"],
        ["--resume"],
        ["resume", "--flag"],
    ],
)
def test_validate_seat_resume_argv_rejects_bare_resume_forms(argv: list[str]) -> None:
    with pytest.raises(
        claudex.ClaudexError,
        match=r"claudex: --seat requires an explicit session id",
    ):
        claudex.validate_seat_resume_argv(argv)


def test_run_seat_rejects_continue_before_subprocess(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(claudex, "resolve_claude_account", lambda slug=None: _fake_claude_account())
    monkeypatch.setattr(claudex.subprocess, "run", lambda *args, **kwargs: pytest.fail("no subprocess"))

    with pytest.raises(claudex.ClaudexError, match=r"explicit session id"):
        claudex.run(["--seat", "--model", "sol", "--continue"])


def test_run_seat_uses_cwd_not_resume_relocated_project(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
) -> None:
    monkeypatch.chdir(tmp_path)
    calls: list[list[str]] = []

    def fake_run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
        calls.append(command)
        return subprocess.CompletedProcess(command, 0)

    monkeypatch.setattr(claudex, "resolve_claude_account", lambda slug=None: _fake_claude_account())
    monkeypatch.setattr(claudex, "resolve_seat_remote_binary", lambda: "/bin/seat-remote")
    monkeypatch.setattr(claudex.subprocess, "run", fake_run)

    claudex.run(["--seat", "--model", "luna", "resume", "session-abc"])

    assert calls[0][calls[0].index("--project") + 1] == str(tmp_path)
