from unittest.mock import MagicMock, mock_open, patch

from sqgen_risk.client import Client
from tests.conftest import TEST_EMAIL, TEST_PASSWORD, TEST_TOKEN


@patch("sqgen_risk.client.requests.Session")
def test_full_workflow(mock_session) -> None:
    """Test the full workflow from authentication to results retrieval."""
    # Setup mock responses
    # Auth response
    auth_response = MagicMock()
    auth_response.status_code = 200
    auth_response.json.return_value = {"session": {"access_token": TEST_TOKEN}}

    # Models response
    models_response = MagicMock()
    models_response.status_code = 200
    models_response.json.return_value = [{"id": 1, "model_id": "model-1", "user_id": "user-1", "name": "Test Model"}]

    # Create inference response
    create_inference_response = MagicMock()
    create_inference_response.status_code = 201
    create_inference_response.json.return_value = {
        "id": 1,
        "user_id": "user-1",
        "inference_request_id": "request-1",
        "model_id": "model-1",
        "created_at": "2025-06-29T12:00:00",
    }

    # Result response
    result_response = MagicMock()
    result_response.status_code = 200
    result_response.content = b"result data"

    # Setup session mock to return different responses for different calls
    session_mock = MagicMock()
    session_mock.post.side_effect = [auth_response, create_inference_response]
    session_mock.get.side_effect = [models_response, result_response]
    mock_session.return_value = session_mock

    # Execute the workflow
    with patch("builtins.open", mock_open(read_data="test data")):
        # Initialize client with custom settings
        client = Client()

        # Authenticate
        token = client.authenticate(email=TEST_EMAIL, password=TEST_PASSWORD)
        assert token == TEST_TOKEN

        # List models
        models = client.list_models()
        assert len(models) == 1
        assert models[0].name == "Test Model"

        # Create inference
        inference = client.create_inference(model_id="model-1", file_path="data.csv")
        assert inference.inference_request_id == "request-1"

        # Get result
        result = client.get_inference_result(inference_request_id="request-1")
        assert result == b"result data"
