"""E2E: Async/concurrency optimization."""

from __future__ import annotations

import os
from pathlib import Path

from .utilities import (
    CoverageExpectation,
    E2ETestConfig,
    run_optimization,
    run_with_retries,
)

_FIXTURES = (
    Path(__file__).resolve().parent.parent
    / "code_to_optimize"
    / "code_directories"
    / "async_e2e"
)


def _run(expected_improvement_pct: int) -> bool:
    config = E2ETestConfig(
        file_path=Path("main.py"),
        min_improvement_x=0.1,
        expected_acceptance_reason="concurrency",
        coverage_expectations=(
            CoverageExpectation(
                function_name="retry_with_backoff",
                expected_coverage=100.0,
                expected_lines=(
                    6,
                    7,
                    8,
                    9,
                    10,
                    11,
                    12,
                    13,
                    14,
                    15,
                    16,
                ),
            ),
        ),
    )
    return run_optimization(
        _FIXTURES,
        config,
        expected_improvement_pct,
    )


def test_async() -> None:
    """Optimize async retry-with-backoff pattern."""
    pct = int(os.getenv("EXPECTED_IMPROVEMENT_PCT", "10"))
    assert 0 == run_with_retries(_run, pct)


if __name__ == "__main__":
    raise SystemExit(
        run_with_retries(
            _run,
            int(os.getenv("EXPECTED_IMPROVEMENT_PCT", "10")),
        ),
    )
