from __future__ import annotations

from types import SimpleNamespace

import pytest

from worai.core.url_sources import sheets
from worai.errors import UsageError


def test_extract_and_is_spreadsheet_source() -> None:
    assert sheets.extract_spreadsheet_id("https://docs.google.com/spreadsheets/d/abc123-XYZ_/edit") == "abc123-XYZ_"
    assert sheets.extract_spreadsheet_id("a" * 25) == "a" * 25
    assert sheets.extract_spreadsheet_id("not-a-sheet") is None
    assert sheets.is_spreadsheet_source("a" * 25) is True
    assert sheets.is_spreadsheet_source("x") is False


def test_load_urls_from_sheet_paths(monkeypatch: pytest.MonkeyPatch) -> None:
    class _Session:
        def __init__(self, _creds):
            pass

        def get(self, url: str):
            if "missing-url-col" in url:
                return SimpleNamespace(status_code=200, json=lambda: {"values": [["name"], ["x"]]})
            if "empty" in url:
                return SimpleNamespace(status_code=200, json=lambda: {"values": []})
            if "bad-status" in url:
                return SimpleNamespace(status_code=500, text="boom", json=lambda: {})
            return SimpleNamespace(
                status_code=200,
                json=lambda: {
                    "values": [["url", "title"], [" https://a.com ", "A"], ["", "B"], ["https://b.com", "B"]]
                },
            )

    monkeypatch.setattr(sheets, "load_google_credentials", lambda **_k: object())
    monkeypatch.setattr(sheets, "AuthorizedSession", _Session)

    with pytest.raises(UsageError, match="Invalid Google Sheets source"):
        sheets.load_urls_from_sheet("invalid", "Sheet1", client_secrets=None, token="t.json", port=8080)

    with pytest.raises(RuntimeError, match="Failed to read source spreadsheet values"):
        sheets.load_urls_from_sheet("bad-status" + "x" * 20, "Sheet1", client_secrets=None, token="t.json", port=8080)

    with pytest.raises(UsageError, match="missing required 'url' column"):
        sheets.load_urls_from_sheet("missing-url-col" + "x" * 20, "Sheet1", client_secrets=None, token="t.json", port=8080)

    assert sheets.load_urls_from_sheet("empty" + "x" * 20, "Sheet1", client_secrets=None, token="t.json", port=8080) == []

    urls = sheets.load_urls_from_sheet("ok" + "x" * 20, "Sheet1", client_secrets=None, token="t.json", port=8080)
    assert urls == ["https://a.com", "https://b.com"]
