"""Tests for the CLI backend registry."""

from __future__ import annotations

from pathlib import Path

import pytest

from github_app.backends import ClaudeBackend, CodexBackend, get_backend


def test_claude_backend_build_cmd():
    backend = ClaudeBackend(name="claude")
    cmd, cwd = backend.build_cmd(
        cli="claude",
        model="claude-sonnet-4-6",
        prompt="review this",
        repo_dir=Path("/tmp/repo"),
        plugin_dir=Path("/tmp/plugins"),
    )
    assert cmd == [
        "claude",
        "-p",
        "review this",
        "--model",
        "claude-sonnet-4-6",
        "--plugin-dir",
        "/tmp/plugins",
    ]
    assert cwd == "/tmp/repo"


def test_claude_backend_no_plugin_dir():
    backend = ClaudeBackend(name="claude")
    cmd, cwd = backend.build_cmd(
        cli="claude",
        model="claude-sonnet-4-6",
        prompt="review this",
        repo_dir=Path("/tmp/repo"),
    )
    assert "--plugin-dir" not in cmd
    assert cwd == "/tmp/repo"


def test_claude_backend_build_edit_cmd_default_agent():
    backend = ClaudeBackend(name="claude")
    cmd, cwd = backend.build_edit_cmd(
        cli="claude",
        model="claude-sonnet-4-6",
        prompt="CI: process .codeflash/ci-context.json",
        repo_dir=Path("/tmp/repo"),
        plugin_dir=Path("/tmp/plugins"),
    )
    assert cmd == [
        "claude",
        "-p",
        "CI: process .codeflash/ci-context.json",
        "--model",
        "claude-sonnet-4-6",
        "--agent",
        "codeflash-ci",
        "--max-turns",
        "200",
        "--dangerously-skip-permissions",
        "--plugin-dir",
        "/tmp/plugins",
    ]
    assert cwd == "/tmp/repo"


def test_claude_backend_build_edit_cmd_custom_agent():
    backend = ClaudeBackend(name="claude")
    cmd, _cwd = backend.build_edit_cmd(
        cli="claude",
        model="claude-sonnet-4-6",
        prompt="optimize this",
        repo_dir=Path("/tmp/repo"),
        plugin_dir=Path("/tmp/plugins"),
        agent="codeflash-deep",
    )
    assert "--agent" in cmd
    idx = cmd.index("--agent")
    assert cmd[idx + 1] == "codeflash-deep"


def test_codex_backend_build_cmd():
    backend = CodexBackend(name="codex")
    cmd, cwd = backend.build_cmd(
        cli="codex",
        model="gpt-5.4",
        prompt="review this",
        repo_dir=Path("/tmp/repo"),
        plugin_dir=Path("/tmp/plugins"),
    )
    assert cmd == [
        "codex",
        "exec",
        "--model",
        "gpt-5.4",
        "--full-auto",
        "-C",
        "/tmp/repo",
        "-o",
        "/dev/stdout",
        "review this",
    ]
    assert cwd is None


def test_get_backend_known():
    assert get_backend("claude").name == "claude"
    assert get_backend("codex").name == "codex"


def test_get_backend_unknown_raises():
    with pytest.raises(ValueError, match="Unknown backend 'gemini'"):
        get_backend("gemini")
