"""Tests for provider plugin behavior and fallback logic."""

from __future__ import annotations

import os
import unittest

from kiessclaw.providers.apollo import ApolloProvider
from kiessclaw.providers.hunter import HunterProvider
from kiessclaw.providers.mock import MockProvider
from kiessclaw.providers.models import ProviderResult
from kiessclaw.providers.registry import list_providers


class ProviderPluginTest(unittest.TestCase):
    """Validate provider result schema and default fallback flow."""

    def setUp(self) -> None:
        """Clear provider API keys for deterministic fallback tests."""
        for key in ("HUNTER_API_KEY", "APOLLO_API_KEY", "CLAY_API_KEY", "HUBSPOT_API_KEY"):
            os.environ.pop(key, None)

    def test_mock_provider_always_ok(self) -> None:
        """Mock provider should always return successful deterministic payloads."""
        provider = MockProvider({})
        found = provider.find_email("Jane", "Doe", "acme.com")
        enriched = provider.enrich_contact("jane.doe@acme.com")
        self.assertTrue(found.ok)
        self.assertTrue(enriched.ok)
        self.assertEqual("mock", found.provider)
        self.assertEqual(0.1, found.confidence)

    def test_hunter_without_key_falls_back_to_mock(self) -> None:
        """Hunter provider without API key should silently use mock behavior."""
        provider = HunterProvider({})
        result = provider.find_email("Alex", "Kim", "acme.com")
        self.assertTrue(result.ok)
        self.assertEqual("mock", result.provider)

    def test_apollo_without_key_falls_back_to_mock(self) -> None:
        """Apollo provider without API key should silently use mock behavior."""
        provider = ApolloProvider({})
        result = provider.enrich_contact("alex.kim@acme.com")
        self.assertTrue(result.ok)
        self.assertEqual("mock", result.provider)

    def test_mock_health_check_is_true(self) -> None:
        """Mock provider health check should always be green."""
        self.assertTrue(MockProvider({}).health_check())

    def test_provider_result_schema(self) -> None:
        """ProviderResult dataclass should expose the expected fields."""
        result = ProviderResult(ok=True, data={"email": "x@y.com"}, provider="mock", confidence=0.1)
        self.assertTrue(result.ok)
        self.assertEqual("mock", result.provider)
        self.assertIsNone(result.error)
        self.assertAlmostEqual(0.1, result.confidence)

    def test_provider_registry_includes_hubspot(self) -> None:
        """Built-in provider registry should include HubSpot CRM provider."""
        self.assertIn("hubspot", list_providers())


if __name__ == "__main__":
    unittest.main()
