"""Tests for shared agentic CLI helper utilities."""

from __future__ import annotations

import click
import pytest

from centris_sdk.cli.commands.agentic.common import (
    DEFAULT_API_KEY,
    DEFAULT_API_URL,
    create_api_client,
    get_api_key,
    get_api_url,
    parse_json_object,
)


class _ConfigLoader:
    def __init__(self, values: dict[str, str]):
        self._values = values

    def get(self, key: str, default: str | None = None) -> str | None:
        return self._values.get(key, default)


class _Deps:
    def __init__(self, values: dict[str, str]):
        self.config_loader = _ConfigLoader(values)


def _ctx(config_values: dict[str, str] | None = None) -> click.Context:
    ctx = click.Context(click.Command("test"))
    ctx.obj = {}
    if config_values is not None:
        ctx.obj["deps"] = _Deps(config_values)
    return ctx


def test_get_api_key_prefers_override(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("CENTRIS_API_KEY", "ck_env")
    ctx = _ctx({"CENTRIS_API_KEY": "ck_config"})
    assert get_api_key(ctx, "ck_override") == "ck_override"


def test_get_api_key_prefers_env_over_config(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("CENTRIS_API_KEY", "ck_env")
    ctx = _ctx({"CENTRIS_API_KEY": "ck_config"})
    assert get_api_key(ctx) == "ck_env"


def test_get_api_key_uses_config_when_env_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("CENTRIS_API_KEY", raising=False)
    ctx = _ctx({"CENTRIS_API_KEY": "ck_config"})
    assert get_api_key(ctx) == "ck_config"


def test_get_api_key_uses_default_without_env_or_config(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.delenv("CENTRIS_API_KEY", raising=False)
    assert get_api_key(_ctx()) == DEFAULT_API_KEY


def test_get_api_url_prefers_env_over_config(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("CENTRIS_API_URL", "http://env.example")
    ctx = _ctx({"CENTRIS_API_URL": "http://config.example"})
    assert get_api_url(ctx) == "http://env.example"


def test_get_api_url_uses_config_when_env_missing(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("CENTRIS_API_URL", raising=False)
    ctx = _ctx({"CENTRIS_API_URL": "http://config.example"})
    assert get_api_url(ctx) == "http://config.example"


def test_get_api_url_uses_default_without_env_or_config(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.delenv("CENTRIS_API_URL", raising=False)
    assert get_api_url(_ctx()) == DEFAULT_API_URL


def test_parse_json_object_returns_empty_dict_for_none() -> None:
    assert parse_json_object(None, "metadata") == {}


def test_parse_json_object_parses_object() -> None:
    assert parse_json_object('{"a": 1}', "metadata") == {"a": 1}


def test_parse_json_object_rejects_invalid_json() -> None:
    with pytest.raises(click.ClickException, match="metadata must be valid JSON"):
        parse_json_object("{invalid", "metadata")


def test_parse_json_object_rejects_non_object() -> None:
    with pytest.raises(click.ClickException, match="metadata must be a JSON object"):
        parse_json_object('["a"]', "metadata")


def test_create_api_client_uses_resolved_config(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.delenv("CENTRIS_API_KEY", raising=False)
    monkeypatch.delenv("CENTRIS_API_URL", raising=False)
    ctx = _ctx(
        {
            "CENTRIS_API_KEY": "ck_from_config",
            "CENTRIS_API_URL": "http://127.0.0.1:18789",
        }
    )

    client = create_api_client(ctx, key=None, base_url=None, timeout=45)

    assert client.api_key == "ck_from_config"
    assert client.base_url == "http://127.0.0.1:18789"
    assert client.timeout == 45.0
