from __future__ import annotations

import json


from aegro.cli import app


class TestFarmsList:
    def test_lists_farms_json(self, runner, mock_settings, temp_state):
        result = runner.invoke(app, ["farms", "list"])
        assert result.exit_code == 0
        data = json.loads(result.stdout)
        names = [f["name"] for f in data]
        assert "Fazenda Norte" in names
        assert "Fazenda Sul" in names

    def test_lists_farms_marks_active(self, runner, mock_settings, temp_state):
        runner.invoke(app, ["farms", "select", "Fazenda Sul"])
        result = runner.invoke(app, ["farms", "list"])
        data = json.loads(result.stdout)
        active = [f for f in data if f["active"]]
        assert len(active) == 1
        assert active[0]["name"] == "Fazenda Sul"


class TestFarmsSelect:
    def test_select_valid_farm(self, runner, mock_settings, temp_state):
        result = runner.invoke(app, ["farms", "select", "Fazenda Sul"])
        assert result.exit_code == 0
        assert "Fazenda Sul" in result.stdout

    def test_select_invalid_farm(self, runner, mock_settings, temp_state):
        result = runner.invoke(app, ["farms", "select", "Inexistente"])
        assert result.exit_code == 1


class TestFarmsInfo:
    def test_info_no_farm_selected(self, runner, mock_settings, temp_state):
        result = runner.invoke(app, ["farms", "info"])
        assert result.exit_code != 0

    def test_info_shows_farm_data(self, runner, mock_settings, mock_client, temp_state):
        mock_client.get.return_value = {"name": "Fazenda Sul", "area": 1200}
        runner.invoke(app, ["farms", "select", "Fazenda Sul"])
        result = runner.invoke(app, ["farms", "info"])
        assert result.exit_code == 0
        data = json.loads(result.stdout)
        assert data["name"] == "Fazenda Sul"
        mock_client.get.assert_called_once_with("/pub/v1/farms", api_key="key-1")
