from datetime import date
from pathlib import Path
import urllib.error

from psx_signal.config import DataConfig
from psx_signal.data.providers.psx_provider import PsxProvider


class _Response:
    def __enter__(self):
        return self

    def __exit__(self, *args):
        return False

    def read(self) -> bytes:
        return b"SCRIP,OPEN,HIGH,LOW,CURRENT,VOLUME\nSYS,1,2,1,2,10\n"


def test_licensed_fetch_retries_and_caches(monkeypatch, tmp_path: Path) -> None:
    calls = []

    def fake_urlopen(request, timeout):
        calls.append((request.full_url, timeout))
        if len(calls) == 1:
            raise urllib.error.URLError("temporary")
        return _Response()

    monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
    provider = PsxProvider(DataConfig(
        inbox=str(tmp_path), licensed_url_template="https://licensed.example/{kind}/{date}.csv",
        request_retries=2, retry_backoff_seconds=0, rate_limit_seconds=0, request_timeout_seconds=7,
    ))
    artifact = provider.fetch_artifact(date(2026, 8, 18), "equities")
    assert artifact is not None
    assert len(calls) == 2
    assert calls[-1] == ("https://licensed.example/equities/2026-08-18.csv", 7)
    assert artifact.path.read_bytes().startswith(b"SCRIP")


def test_no_undocumented_url_means_file_only_mode(tmp_path: Path) -> None:
    provider = PsxProvider(DataConfig(inbox=str(tmp_path), licensed_url_template=""))
    assert provider.fetch_artifact(date(2026, 8, 18)) is None

