from __future__ import annotations

from pathlib import Path

import pytest

from worai.core.url_sources import UrlSourceOptions, resolve_url_records, resolve_urls
from worai.core.url_sources.file import load_urls_from_file
from worai.errors import UsageError


def test_load_urls_from_file_txt_dedupes_and_ignores_comments(tmp_path: Path) -> None:
    path = tmp_path / "urls.txt"
    path.write_text(
        """
        # comment
        https://example.com/a

        https://example.com/a
        https://example.com/b
        """,
        encoding="utf-8",
    )

    urls = load_urls_from_file(path)
    assert urls == ["https://example.com/a", "https://example.com/b"]


def test_load_urls_from_file_csv_requires_url_column(tmp_path: Path) -> None:
    path = tmp_path / "urls.csv"
    path.write_text("page\nhttps://example.com/a\n", encoding="utf-8")

    with pytest.raises(UsageError):
        load_urls_from_file(path)


def test_resolver_uses_sheets_loader(monkeypatch: pytest.MonkeyPatch) -> None:
    options = UrlSourceOptions(
        source="https://docs.google.com/spreadsheets/d/1Oy8eD6gLwW7XLwIMy0Dli-NJF9V4YMLxbdJdphjtCf8/edit",
        sheet_name="URLs_US",
    )

    monkeypatch.setattr(
        "worai.core.url_sources.resolver.load_urls_from_sheet",
        lambda *args, **kwargs: ["https://example.com/a", "https://example.com/a", "https://example.com/b"],
    )

    urls = resolve_urls(options)
    assert urls == ["https://example.com/a", "https://example.com/b"]


def test_resolver_requires_sheet_name_for_sheet_source() -> None:
    options = UrlSourceOptions(
        source="https://docs.google.com/spreadsheets/d/1Oy8eD6gLwW7XLwIMy0Dli-NJF9V4YMLxbdJdphjtCf8/edit"
    )

    with pytest.raises(UsageError):
        resolve_urls(options)


def test_resolver_uses_file_loader_for_local_file(tmp_path: Path) -> None:
    path = tmp_path / "urls.txt"
    path.write_text("https://example.com/a\nhttps://example.com/b\n", encoding="utf-8")

    urls = resolve_urls(UrlSourceOptions(source=str(path)))
    assert urls == ["https://example.com/a", "https://example.com/b"]


def test_resolver_uses_sitemap_loader_for_remote_source(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(
        "worai.core.url_sources.resolver.load_urls_from_sitemap",
        lambda source, timeout: ["https://example.com/a", "https://example.com/b"],
    )

    urls = resolve_urls(UrlSourceOptions(source="https://example.com/sitemap.xml"))
    assert urls == ["https://example.com/a", "https://example.com/b"]


def test_resolver_supports_debug_cloud_records(tmp_path: Path) -> None:
    ttl = tmp_path / "debug.ttl"
    ttl.write_text(
        """
        @prefix schema: <http://schema.org/> .
        @prefix seovoc: <https://w3id.org/seovoc/> .

        <https://data.example/entity/1>
          schema:url "https://example.com/a" ;
          seovoc:html "<html><body>ok</body></html>" .
        """,
        encoding="utf-8",
    )

    records = resolve_url_records(
        UrlSourceOptions(
            source=str(ttl),
            source_type="debug-cloud",
        )
    )

    assert len(records) == 1
    assert records[0].url == "https://example.com/a"
    assert records[0].html == "<html><body>ok</body></html>"
    assert records[0].source_type == "debug-cloud"


def test_resolver_debug_cloud_prefers_record_with_html(tmp_path: Path) -> None:
    ttl = tmp_path / "debug.ttl"
    ttl.write_text(
        """
        @prefix schema: <http://schema.org/> .
        @prefix seovoc: <https://w3id.org/seovoc/> .

        <https://data.example/entity/no-html>
          schema:url "https://example.com/a" .

        <https://data.example/entity/with-html>
          schema:url "https://example.com/a" ;
          seovoc:html "<html><body>from-debug</body></html>" .
        """,
        encoding="utf-8",
    )

    records = resolve_url_records(
        UrlSourceOptions(
            source=str(ttl),
            source_type="debug-cloud",
        )
    )

    assert len(records) == 1
    assert records[0].url == "https://example.com/a"
    assert records[0].html == "<html><body>from-debug</body></html>"
