from __future__ import annotations

import asyncio

from thread_downloader import DownloadConfig, Downloader, DownloadTask

from conftest import run_test_server


def test_global_semaphore_limits_multi_instance_parallel(tmp_path, sample_data: bytes) -> None:
    Downloader.set_global_concurrency_limit(1)

    try:
        with run_test_server(
            support_range=False,
            data=sample_data,
            delay_seconds=0.15,
        ) as (url, state):
            downloader_a = Downloader(DownloadConfig(workers=4))
            downloader_b = Downloader(DownloadConfig(workers=4))

            file_a = tmp_path / "a.bin"
            file_b = tmp_path / "b.bin"
            async def run_parallel() -> None:
                await asyncio.gather(
                    downloader_a.download(DownloadTask(url, str(file_a))),
                    downloader_b.download(DownloadTask(url, str(file_b))),
                )

            asyncio.run(run_parallel())
            assert file_a.read_bytes() == sample_data
            assert file_b.read_bytes() == sample_data
            assert state.max_active_requests <= 1
    finally:
        Downloader.set_global_concurrency_limit(4)
