import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from worai.core.dil_import import (
    _sha1_url,
    _is_collection_page_only,
    resolve_iris_for_urls,
    load_rows,
    import_dils,
    DilImportOptions,
)


def test_sha1_url():
    url = "https://example.com"
    expected = "327c3fda87ce286848a574982ddd0b7c7487f816"
    assert _sha1_url(url) == expected


def test_is_collection_page_only():
    assert _is_collection_page_only(["http://schema.org/CollectionPage"]) is True
    assert _is_collection_page_only(["http://schema.org/Person"]) is False
    assert (
        _is_collection_page_only(
            ["http://schema.org/CollectionPage", "http://schema.org/Person"]
        )
        is False
    )
    assert _is_collection_page_only(None) is False


def test_resolve_iris_for_urls_new_entities(monkeypatch):
    def mock_fetch_entities(api_key, urls):
        return {"data": {"entities": []}}

    monkeypatch.setattr(
        "worai.core.dil_import.fetch_entities_for_urls", mock_fetch_entities
    )

    dataset_uri = "https://data.wordlift.io/base"
    urls = ["https://site.com/page1"]

    resolved, reused = resolve_iris_for_urls("fake_key", dataset_uri, urls)

    assert urls[0] in resolved
    assert resolved[urls[0]].endswith(_sha1_url(urls[0]))
    assert urls[0] not in reused


def test_load_rows(tmp_path):
    d = tmp_path / "test.csv"
    d.write_text("source_url,target_url\nurl1,url2", encoding="utf-8-sig")

    rows, fieldnames = load_rows(str(d))
    assert len(rows) == 1
    assert fieldnames == ["source_url", "target_url"]


@pytest.mark.asyncio
async def test_import_dils_success(monkeypatch, tmp_path):
    csv_file = tmp_path / "input.csv"
    csv_file.write_text(
        "source_url,target_url,target_position,target_anchor_text\n"
        "https://s.com,https://t.com,1,Link",
        encoding="utf-8-sig",
    )

    options = DilImportOptions(api_key="test_key", csv_file=str(csv_file))

    mock_client = MagicMock()
    mock_client.close = AsyncMock()
    monkeypatch.setattr("worai.core.dil_import._build_client", lambda key: mock_client)

    async def mock_fetch_acc(key, client):
        return "https://data.io/dataset"

    monkeypatch.setattr("worai.core.dil_import.fetch_account", mock_fetch_acc)

    def mock_resolve(api_key, dataset_uri, urls):
        return ({"https://s.com": "https://data.io/iri"}, set())

    monkeypatch.setattr("worai.core.dil_import.resolve_iris_for_urls", mock_resolve)

    mock_api_instance = MagicMock()
    mock_api_instance.create_or_update_entities = AsyncMock()

    monkeypatch.setattr("wordlift_client.EntitiesApi", lambda client: mock_api_instance)

    result = await import_dils(options)

    assert result == 0
    assert mock_api_instance.create_or_update_entities.called
    assert mock_client.close.called
