"""
NTLabs SDK - Test Configuration
Shared fixtures and mocks for all tests.

Author: Anderson Henrique da Silva
Location: Minas Gerais, Brasil
"""

from typing import Any
from unittest.mock import MagicMock, patch

import pytest

# =============================================================================
# API Response Fixtures
# =============================================================================


@pytest.fixture
def chat_response() -> dict[str, Any]:
    """Mock chat completion response."""
    return {
        "id": "chat-123",
        "choices": [
            {
                "message": {"content": "Olá! Como posso ajudar?"},
                "finish_reason": "stop",
            }
        ],
        "model": "maritaca-sabia-3",
        "usage": {
            "prompt_tokens": 10,
            "completion_tokens": 20,
            "total_tokens": 30,
        },
    }


@pytest.fixture
def email_response() -> dict[str, Any]:
    """Mock email send response."""
    return {
        "id": "email-456",
        "status": "sent",
        "latency_ms": 150,
        "cost_brl": 0.001,
    }


@pytest.fixture
def cnpj_response() -> dict[str, Any]:
    """Mock CNPJ lookup response."""
    return {
        "cnpj": "12345678000190",
        "razao_social": "EMPRESA TESTE LTDA",
        "nome_fantasia": "Empresa Teste",
        "situacao": "ATIVA",
        "data_situacao": "2020-01-01",
        "tipo": "MATRIZ",
        "porte": "PEQUENO",
        "natureza_juridica": "206-2 - Sociedade Empresária Limitada",
        "atividade_principal": [
            {"codigo": "6201-5/01", "descricao": "Desenvolvimento de software"}
        ],
        "atividades_secundarias": [],
        "endereco": {
            "logradouro": "Rua Teste",
            "numero": "123",
            "bairro": "Centro",
            "municipio": "Belo Horizonte",
            "uf": "MG",
            "cep": "30130-000",
        },
        "telefone": "(31) 3333-4444",
        "email": "contato@empresateste.com.br",
        "capital_social": "100000.00",
        "data_abertura": "2015-06-15",
        "latency_ms": 250,
        "cost_brl": 0.01,
    }


@pytest.fixture
def cep_response() -> dict[str, Any]:
    """Mock CEP lookup response."""
    return {
        "cep": "01310-100",
        "logradouro": "Avenida Paulista",
        "complemento": "",
        "bairro": "Bela Vista",
        "municipio": "São Paulo",
        "uf": "SP",
        "ibge": "3550308",
        "ddd": "11",
        "latency_ms": 50,
        "cost_brl": 0.001,
    }


@pytest.fixture
def cpf_response() -> dict[str, Any]:
    """Mock CPF validation response."""
    return {
        "cpf": "12345678909",
        "valid": True,
        "reason": None,
        "latency_ms": 10,
        "cost_brl": 0.0,
    }


@pytest.fixture
def transcription_response() -> dict[str, Any]:
    """Mock transcription response."""
    return {
        "text": "Olá, bom dia. Como você está?",
        "duration_seconds": 3.5,
        "language": "pt",
        "confidence": 0.95,
        "words": [
            {"word": "Olá", "start": 0.0, "end": 0.5},
            {"word": "bom", "start": 0.6, "end": 0.9},
            {"word": "dia", "start": 1.0, "end": 1.3},
        ],
        "latency_ms": 500,
        "cost_brl": 0.05,
    }


@pytest.fixture
def usage_response() -> dict[str, Any]:
    """Mock billing usage response."""
    return {
        "total_requests": 1000,
        "total_tokens": 500000,
        "total_cost": 25.50,
        "included_requests": 10000,
        "included_tokens": 1000000,
        "requests_percentage": 10.0,
        "tokens_percentage": 50.0,
        "period_start": "2026-01-01",
        "period_end": "2026-01-31",
        "days_remaining": 15,
    }


@pytest.fixture
def subscription_response() -> dict[str, Any]:
    """Mock subscription response."""
    return {
        "id": "sub-123",
        "plan": {"name": "pro", "id": "plan-pro"},
        "status": "active",
        "billing_cycle": "monthly",
        "current_period_start": "2026-01-01",
        "current_period_end": "2026-01-31",
    }


@pytest.fixture
def credits_response() -> dict[str, Any]:
    """Mock credits response."""
    return {
        "current_balance": 100.00,
        "credit_limit": 500.00,
        "available": 100.00,
    }


@pytest.fixture
def ibge_estados_response() -> dict[str, Any]:
    """Mock IBGE estados response."""
    return {
        "estados": [
            {"id": 31, "sigla": "MG", "nome": "Minas Gerais"},
            {"id": 35, "sigla": "SP", "nome": "São Paulo"},
            {"id": 33, "sigla": "RJ", "nome": "Rio de Janeiro"},
        ],
        "latency_ms": 50,
        "cost_brl": 0.0,
    }


@pytest.fixture
def ibge_municipios_response() -> dict[str, Any]:
    """Mock IBGE municipios response."""
    return {
        "municipios": [
            {"id": 3106200, "nome": "Belo Horizonte"},
            {"id": 3106705, "nome": "Betim"},
            {"id": 3118601, "nome": "Contagem"},
        ],
        "uf": {"id": 31, "sigla": "MG", "nome": "Minas Gerais"},
        "latency_ms": 100,
        "cost_brl": 0.0,
    }


# =============================================================================
# Mock Client Fixture
# =============================================================================


@pytest.fixture
def mock_client():
    """Create a mock NTLClient for testing."""
    with patch("ntlabs.client.httpx.Client") as mock_httpx:
        mock_http_client = MagicMock()
        mock_httpx.return_value = mock_http_client

        # Import after patching
        from ntlabs import NTLClient

        client = NTLClient(api_key="ntl_test_123")
        client._mock_http = mock_http_client

        yield client


@pytest.fixture
def mock_response():
    """Factory for creating mock HTTP responses."""

    def _create_response(json_data: dict, status_code: int = 200):
        response = MagicMock()
        response.status_code = status_code
        response.json.return_value = json_data
        response.content = b'{"data": "test"}'
        response.headers = {}
        return response

    return _create_response


# =============================================================================
# Environment Fixtures
# =============================================================================


@pytest.fixture(autouse=True)
def clean_env(monkeypatch):
    """Clean environment variables for each test."""
    monkeypatch.delenv("NTL_API_KEY", raising=False)
    monkeypatch.delenv("NTL_API_URL", raising=False)
    monkeypatch.delenv("NTL_INTERNAL_URL", raising=False)
