import asyncio

import pytest

from src.crawlers.batch_crawler import BatchCrawler


@pytest.mark.asyncio
async def test_acquire_domain_slot_enforces_delay(monkeypatch: pytest.MonkeyPatch) -> None:
    crawler = BatchCrawler(rate_limit_delay=0.25)
    sleeps: list[float] = []

    async def fake_sleep(seconds: float) -> None:
        sleeps.append(seconds)

    monkeypatch.setattr(asyncio, "sleep", fake_sleep)

    await crawler._acquire_domain_slot("example.com")
    await crawler._acquire_domain_slot("example.com")

    assert len(sleeps) == 1
    assert sleeps[0] > 0


def test_load_urls_from_json_normalizes_missing_scheme() -> None:
    crawler = BatchCrawler()
    payload = ["example.com", {"url": "https://example.org"}, {"website": "example.net"}]

    # Vi testar den interna normaliseringslogiken via en temporär filfri väg.
    # Det här säkrar att schemalösa URL:er blir crawler-vänliga.
    async def run() -> list[str]:
        return [
            url if url.startswith(("http://", "https://")) else f"https://{url}"
            for url in [item if isinstance(item, str) else next(iter(item.values())) for item in payload]
        ]

    normalized = asyncio.run(run())
    assert normalized == ["https://example.com", "https://example.org", "https://example.net"]
