from __future__ import annotations

import pytest
from pydantic import ValidationError

from supply_infra.config import InfraSettings


def _settings(**overrides: object) -> InfraSettings:
    values: dict[str, object] = {
        "PROCESS_ROLE": "api",
        "MYSQL_CONNECTION_BUDGET": 40,
        "MYSQL_POOL_SIZE_API": 6,
        "MYSQL_POOL_SIZE_CONTROL": 1,
        "MYSQL_OPERATIONAL_RESERVE": 4,
        "MYSQL_MAX_OVERFLOW": 0,
        "PIPELINE_WORKER_PROCESSES": 4,
        "PIPELINE_MAX_ACTIVE_STEPS": 4,
    }
    values.update(overrides)
    return InfraSettings(_env_file=None, **values)


def test_standard_connection_profile_uses_twenty_of_forty() -> None:
    settings = _settings()
    assert settings.pipeline_required_connections == 20
    assert settings.mysql_connection_budget == 40


def test_high_concurrency_profile_stays_within_fifty() -> None:
    settings = _settings(
        MYSQL_CONNECTION_BUDGET=50,
        PIPELINE_WORKER_PROCESSES=20,
        PIPELINE_MAX_ACTIVE_STEPS=10,
    )
    assert settings.pipeline_required_connections == 42


def test_connection_budget_rejects_unbounded_twenty_by_twenty() -> None:
    with pytest.raises(ValidationError, match="connection budget exceeded"):
        _settings(
            MYSQL_CONNECTION_BUDGET=50,
            PIPELINE_WORKER_PROCESSES=20,
            PIPELINE_MAX_ACTIVE_STEPS=20,
        )


def test_pool_overflow_must_remain_zero() -> None:
    with pytest.raises(ValidationError, match="MYSQL_MAX_OVERFLOW"):
        _settings(MYSQL_MAX_OVERFLOW=1)
