import json
import respx
import httpx
from click.testing import CliRunner
from rftools._cli import cli

MOCK_RESPONSE = {
    "slug": "vswr-return-loss",
    "values": {"returnLoss": 9.54, "reflectionCoeff": 0.333},
    "warnings": [],
    "errors": [],
}


@respx.mock
def test_calc_command():
    from rftools.client import _DEFAULT_BASE_URL
    respx.post(f"{_DEFAULT_BASE_URL}/calculate").mock(
        return_value=httpx.Response(200, json=MOCK_RESPONSE)
    )
    runner = CliRunner()
    result = runner.invoke(cli, ["calc", "vswr-return-loss", "--vswr", "2.5"])
    assert result.exit_code == 0, result.output
    assert "9.54" in result.output


@respx.mock
def test_calc_command_json():
    from rftools.client import _DEFAULT_BASE_URL
    respx.post(f"{_DEFAULT_BASE_URL}/calculate").mock(
        return_value=httpx.Response(200, json=MOCK_RESPONSE)
    )
    runner = CliRunner()
    result = runner.invoke(cli, ["calc", "vswr-return-loss", "--vswr", "2.5", "--json"])
    assert result.exit_code == 0, result.output
    data = json.loads(result.output)
    assert data["values"]["returnLoss"] == 9.54


def test_list_command():
    runner = CliRunner()
    result = runner.invoke(cli, ["list"])
    assert result.exit_code == 0
    assert "vswr-return-loss" in result.output
    assert "rf" in result.output


def test_list_category_filter():
    runner = CliRunner()
    result = runner.invoke(cli, ["list", "--category", "rf"])
    assert result.exit_code == 0
    assert "vswr-return-loss" in result.output
    # pcb-only calculator should not appear
    assert "trace-width-current" not in result.output


def test_info_command():
    runner = CliRunner()
    result = runner.invoke(cli, ["info", "vswr-return-loss"])
    assert result.exit_code == 0
    assert "INPUTS" in result.output
    assert "vswr" in result.output


def test_version_command():
    runner = CliRunner()
    result = runner.invoke(cli, ["version"])
    assert result.exit_code == 0
    import rftools
    assert rftools.__version__ in result.output
