from __future__ import annotations

import asyncio

from thread_downloader import DownloadConfig, Downloader, DownloadTask

from conftest import run_test_server


def test_mem_assemble_yes_uses_memory_buffer(tmp_path, sample_data: bytes) -> None:
    downloader = Downloader(
        DownloadConfig(
            workers=4,
            mem_assemble=True,
        )
    )
    target = tmp_path / "mem.bin"

    with run_test_server(support_range=True, data=sample_data) as (url, _state):
        task = DownloadTask(url, str(target))
        result = asyncio.run(downloader.download(task))

    assert result.used_multi_thread is True
    assert target.read_bytes() == sample_data
    assert result.bytes_written == len(sample_data)


def test_mem_assemble_no_uses_temp_files(tmp_path, sample_data: bytes) -> None:
    downloader = Downloader(
        DownloadConfig(
            workers=4,
            mem_assemble=False,
        )
    )
    target = tmp_path / "temp_files.bin"

    with run_test_server(support_range=True, data=sample_data) as (url, _state):
        task = DownloadTask(url, str(target))
        result = asyncio.run(downloader.download(task))

    assert result.used_multi_thread is True
    assert target.read_bytes() == sample_data
    assert result.bytes_written == len(sample_data)
