"""Tests for HTML Parse node."""

import pytest

from fw_nodes_core.nodes.html_parse import HTMLParseNode


@pytest.mark.asyncio
async def test_valid_css_selector(node_execution_context):
    """Test extracting elements with a valid CSS selector."""
    node = HTMLParseNode()
    html = "<div><p class='intro'>Hello</p><p>World</p></div>"

    result = await node.execute({"html": html, "selector": "p"}, node_execution_context)

    assert result.count == 2
    assert isinstance(result.elements, list)
    assert len(result.elements) == 2


@pytest.mark.asyncio
async def test_single_match_returns_string(node_execution_context):
    """Single match returns a string, not a list."""
    node = HTMLParseNode()
    html = "<div><h1>Title</h1></div>"

    result = await node.execute({"html": html, "selector": "h1"}, node_execution_context)

    assert result.count == 1
    assert isinstance(result.elements, str)
    assert "Title" in result.elements


@pytest.mark.asyncio
async def test_no_matches_returns_empty(node_execution_context):
    """No matches returns empty string and count 0."""
    node = HTMLParseNode()
    html = "<div><p>Hello</p></div>"

    result = await node.execute({"html": html, "selector": "span"}, node_execution_context)

    assert result.count == 0
    assert result.elements == ""


@pytest.mark.asyncio
async def test_empty_html_raises(node_execution_context):
    """Empty HTML should raise ValueError."""
    node = HTMLParseNode()

    with pytest.raises(ValueError, match="HTML content is required"):
        await node.execute({"html": "", "selector": "div"}, node_execution_context)


@pytest.mark.asyncio
async def test_empty_selector_raises(node_execution_context):
    """Empty selector should raise ValueError."""
    node = HTMLParseNode()

    with pytest.raises(ValueError, match="CSS selector is required"):
        await node.execute({"html": "<div></div>", "selector": ""}, node_execution_context)


@pytest.mark.asyncio
async def test_class_selector(node_execution_context):
    """Test CSS class selector."""
    node = HTMLParseNode()
    html = '<div><span class="highlight">A</span><span>B</span></div>'

    result = await node.execute({"html": html, "selector": "span.highlight"}, node_execution_context)

    assert result.count == 1
    assert "A" in result.elements
