from __future__ import annotations

import wzrd.client as client_module
from wzrd.client import WZRDClient


def _client_with_payload(payload):
    client = WZRDClient()
    client._fetch_payload = lambda: payload  # type: ignore[method-assign]
    return client


def test_pick_prefers_strict_signal_over_observe():
    client = _client_with_payload(
        {
            "count": 2,
            "models": [
                {
                    "model": "moonshotai/Kimi-K2.5",
                    "trend": "surging",
                    "score": 1.0,
                    "action": "observe",
                    "confidence": "low",
                    "platform": "huggingface",
                },
                {
                    "model": "Qwen/Qwen3.5-35B-A3B",
                    "trend": "accelerating",
                    "score": 0.7,
                    "action": "candidate",
                    "confidence": "normal",
                    "platform": "github",
                },
            ],
        }
    )

    choice = client.pick_details("code")

    assert choice.model == "Qwen/Qwen3.5-35B-A3B"
    assert choice.policy == "strict"
    assert choice.signal_model == "Qwen/Qwen3.5-35B-A3B"


def test_pick_uses_task_platform_bias():
    payload = {
        "count": 2,
        "models": [
            {
                "model": "github/model-a",
                "trend": "stable",
                "score": 0.5,
                "action": "candidate",
                "confidence": "normal",
                "platform": "github",
            },
            {
                "model": "openrouter/model-b",
                "trend": "stable",
                "score": 0.5,
                "action": "candidate",
                "confidence": "normal",
                "platform": "openrouter",
            },
        ],
    }

    client = _client_with_payload(payload)

    assert client.pick("code") == "github/model-a"
    assert client.pick("chat") == "openrouter/model-b"


def test_pick_with_candidates_matches_aliases():
    client = _client_with_payload(
        {
            "count": 2,
            "models": [
                {
                    "model": "Qwen/Qwen3.5-9B",
                    "trend": "accelerating",
                    "score": 0.8,
                    "action": "candidate",
                    "confidence": "normal",
                    "platform": "openrouter",
                },
                {
                    "model": "anthropic/claude-sonnet-4.6",
                    "trend": "stable",
                    "score": 0.4,
                    "action": "candidate",
                    "confidence": "normal",
                    "platform": "openrouter",
                },
            ],
        }
    )

    choice = client.pick(
        "code",
        candidates=[
            "openrouter/qwen/qwen3.5-9b",
            "anthropic/claude-sonnet-4.6",
        ],
    )

    assert choice == "openrouter/qwen/qwen3.5-9b"


def test_compare_returns_verdict():
    client = _client_with_payload(
        {
            "count": 2,
            "models": [
                {
                    "model": "Qwen/Qwen3.5-35B-A3B",
                    "trend": "surging",
                    "score": 0.7,
                    "action": "candidate",
                    "confidence": "normal",
                    "platform": "github",
                },
                {
                    "model": "anthropic/claude-sonnet-4.6",
                    "trend": "stable",
                    "score": 0.2,
                    "action": "candidate",
                    "confidence": "normal",
                    "platform": "openrouter",
                },
            ],
        }
    )

    verdict = client.compare("Qwen/Qwen3.5-35B-A3B", "anthropic/claude-sonnet-4.6")

    assert verdict["winner"] == "Qwen/Qwen3.5-35B-A3B"
    assert "stronger momentum" in verdict["verdict"]


def test_compare_unmatched_returns_not_tracked():
    client = _client_with_payload({"count": 0, "models": []})

    verdict = client.compare("not-tracked-a", "not-tracked-b")

    assert verdict["winner"] is None
    assert "tracked" in verdict["verdict"]
    assert verdict["a"]["status"] == "not_tracked"
    assert verdict["b"]["status"] == "not_tracked"


def test_feed_meta_parses_envelope():
    client = _client_with_payload(
        {
            "contract_version": "wzrd.momentum.v1",
            "generated_at": "2026-03-18T23:31:00Z",
            "provenance": {"source": "momentum_aggregator", "root_seq": 1842},
            "count": 0,
            "models": [],
        }
    )

    meta = client.feed_meta()

    assert meta is not None
    assert meta.contract_version == "wzrd.momentum.v1"
    assert meta.generated_at == "2026-03-18T23:31:00Z"
    assert meta.source == "momentum_aggregator"
    assert meta.root_seq == 1842


def test_feed_meta_returns_none_without_envelope():
    client = _client_with_payload({"count": 0, "models": []})

    meta = client.feed_meta()

    assert meta is None


def test_pick_uses_env_api_url_when_not_explicit(monkeypatch):
    captured: dict[str, object] = {}

    class FakePicker:
        def pick(self, **kwargs):
            return "ok"

    def fake_get_client(**kwargs):
        captured.update(kwargs)
        return FakePicker()

    monkeypatch.setenv("WZRD_API_URL", "https://example.test/public")
    monkeypatch.setattr(client_module, "get_client", fake_get_client)

    result = client_module.pick("code")

    assert result == "ok"
    assert captured["api_url"] == "https://example.test/public"


def test_pick_explicit_api_url_overrides_env(monkeypatch):
    captured: dict[str, object] = {}

    class FakePicker:
        def pick(self, **kwargs):
            return "ok"

    def fake_get_client(**kwargs):
        captured.update(kwargs)
        return FakePicker()

    monkeypatch.setenv("WZRD_API_URL", "https://example.test/public")
    monkeypatch.setattr(client_module, "get_client", fake_get_client)

    result = client_module.pick("code", api_url="https://example.test/premium")

    assert result == "ok"
    assert captured["api_url"] == "https://example.test/premium"
