"""
Unit tests for FetchNova provider
"""

import pytest

from oiiai.fetchModelList import FetchNova
from oiiai.fetchModelList.base import FetchBase


class DummyResponse:
    """Mock response object for testing"""
    
    def __init__(self, json_data, status_code: int = 200):
        self._json_data = json_data
        self.status_code = status_code

    def json(self):
        return self._json_data

    def raise_for_status(self):
        if self.status_code >= 400:
            raise Exception(f"HTTP {self.status_code}")


class TestFetchNovaConstructor:
    """Tests for FetchNova constructor and API key handling"""

    def test_constructor_with_explicit_api_key(self):
        """Test constructor accepts explicit API key parameter"""
        fetcher = FetchNova(api_key="test-api-key")
        assert fetcher._api_key == "test-api-key"

    def test_constructor_with_env_var_fallback(self, monkeypatch):
        """Test constructor reads from NOVA_API_KEY env var when no key provided"""
        monkeypatch.setenv("NOVA_API_KEY", "env-api-key")
        fetcher = FetchNova()
        assert fetcher._api_key == "env-api-key"

    def test_constructor_explicit_key_overrides_env_var(self, monkeypatch):
        """Test explicit API key takes precedence over env var"""
        monkeypatch.setenv("NOVA_API_KEY", "env-api-key")
        fetcher = FetchNova(api_key="explicit-key")
        assert fetcher._api_key == "explicit-key"

    def test_constructor_no_key_no_env_var(self, monkeypatch):
        """Test constructor sets empty string when no key available"""
        monkeypatch.delenv("NOVA_API_KEY", raising=False)
        fetcher = FetchNova()
        assert fetcher._api_key == ""


class TestFetchNovaProvider:
    """Tests for FetchNova provider property"""

    def test_provider_returns_nova(self):
        """Test provider property returns 'nova'"""
        fetcher = FetchNova(api_key="test-key")
        assert fetcher.provider == "nova"


class TestFetchNovaInheritance:
    """Tests for FetchNova class inheritance"""

    def test_is_instance_of_fetch_base(self):
        """Test FetchNova is instance of FetchBase"""
        fetcher = FetchNova(api_key="test-key")
        assert isinstance(fetcher, FetchBase)


class TestFetchNovaMissingApiKey:
    """Tests for FetchNova behavior when API key is missing"""

    def test_fetch_models_returns_empty_list_when_no_api_key(self, monkeypatch):
        """Test fetch_models returns empty list when API key is missing"""
        monkeypatch.delenv("NOVA_API_KEY", raising=False)
        fetcher = FetchNova()
        result = fetcher.fetch_models()
        assert result == []

    def test_fetch_models_raw_returns_empty_dict_when_no_api_key(self, monkeypatch):
        """Test fetch_models_raw returns empty dict when API key is missing"""
        monkeypatch.delenv("NOVA_API_KEY", raising=False)
        fetcher = FetchNova()
        result = fetcher.fetch_models_raw()
        assert result == {}


class TestFetchNovaFetchModels:
    """Tests for FetchNova fetch_models method"""

    def test_fetch_models_extracts_ids(self, monkeypatch):
        """Test fetch_models extracts id fields from data array"""
        captured = {}

        def fake_get(url, headers=None, timeout=None):
            captured["url"] = url
            captured["headers"] = headers or {}
            captured["timeout"] = timeout
            return DummyResponse({
                "object": "list",
                "data": [
                    {"id": "model-1", "owned_by": "amazon"},
                    {"id": "model-2", "owned_by": "amazon"},
                    {"name": "no-id-field"}
                ]
            })

        monkeypatch.setattr("oiiai.fetchModelList.nova.requests.get", fake_get)

        fetcher = FetchNova(api_key="test-key")
        models = fetcher.fetch_models()

        assert models == ["model-1", "model-2"]
        assert captured["headers"].get("Authorization") == "Bearer test-key"

    def test_fetch_models_uses_bearer_auth(self, monkeypatch):
        """Test fetch_models sends Authorization header with Bearer token"""
        captured_headers = {}

        def fake_get(url, headers=None, timeout=None):
            captured_headers.update(headers or {})
            return DummyResponse({"data": []})

        monkeypatch.setattr("oiiai.fetchModelList.nova.requests.get", fake_get)

        fetcher = FetchNova(api_key="my-secret-key")
        fetcher.fetch_models()

        assert captured_headers.get("Authorization") == "Bearer my-secret-key"
