import httpx
import pytest

from timesheet import defectdb


CSV = 'Номенклатура,Обработчик\nТовар,Специалист\n'.encode('utf-8')


def test_timeout_uses_complete_csv_from_same_sheet_fallback():
    calls = []
    def respond(request):
        calls.append(str(request.url))
        if len(calls) == 1:
            raise httpx.ReadTimeout('export stalled', request=request)
        return httpx.Response(200, content=CSV, headers={'content-type':'text/csv'})
    with httpx.Client(transport=httpx.MockTransport(respond)) as client:
        assert defectdb.download_handler_csv(client) == CSV
    assert calls == [defectdb.HANDLER_CSV_EXPORT_URL, defectdb.HANDLER_CSV_RETRY_URL]
    assert 'gid=1608899958' in calls[1]
    assert 'limit' not in calls[1]
    assert '/gviz/' not in calls[1]


def test_access_denial_is_not_retried_as_network_failure():
    calls = []
    def respond(request):
        calls.append(request)
        return httpx.Response(403)
    with httpx.Client(transport=httpx.MockTransport(respond)) as client:
        with pytest.raises(ValueError, match='отказал в доступе'):
            defectdb.download_handler_csv(client)
    assert len(calls) == 1


def test_both_timeouts_report_reason_without_claiming_lost_access():
    def respond(request):
        raise httpx.ReadTimeout('stalled', request=request)
    with httpx.Client(transport=httpx.MockTransport(respond)) as client:
        with pytest.raises(ValueError, match='не передал экспорт') as error:
            defectdb.download_handler_csv(client)
    assert 'не изменялись' in str(error.value)


def test_fallback_login_page_never_becomes_import_data():
    calls = []
    def respond(request):
        calls.append(request)
        if len(calls) == 1:
            return httpx.Response(503)
        return httpx.Response(200, text='<html>Login</html>', headers={'content-type':'text/html'})
    with httpx.Client(transport=httpx.MockTransport(respond)) as client:
        with pytest.raises(ValueError, match='запросил вход'):
            defectdb.download_handler_csv(client)
