from aiservice.common.xml_utils import extract_xml_tag


def test_extract_xml_tag_basic() -> None:
    content = "<explain>This is the explanation</explain>"
    result = extract_xml_tag(content, "explain")
    assert result == "This is the explanation"


def test_extract_xml_tag_case_insensitive_default() -> None:
    content = "<EXPLAIN>Mixed case content</EXPLAIN>"
    result = extract_xml_tag(content, "explain")
    assert result == "Mixed case content"


def test_extract_xml_tag_case_sensitive() -> None:
    content = "<EXPLAIN>Content</EXPLAIN>"
    result = extract_xml_tag(content, "explain", case_insensitive=False)
    assert result is None


def test_extract_xml_tag_case_sensitive_match() -> None:
    content = "<explain>Content</explain>"
    result = extract_xml_tag(content, "explain", case_insensitive=False)
    assert result == "Content"


def test_extract_xml_tag_not_found() -> None:
    content = "No tags here"
    result = extract_xml_tag(content, "explain")
    assert result is None


def test_extract_xml_tag_multiline() -> None:
    content = """<code>
def foo():
    return 42
</code>"""
    result = extract_xml_tag(content, "code")
    assert result is not None
    assert "def foo():" in result
    assert "return 42" in result


def test_extract_xml_tag_with_surrounding_text() -> None:
    content = "Some text <result>extracted</result> more text"
    result = extract_xml_tag(content, "result")
    assert result == "extracted"


def test_extract_xml_tag_first_match() -> None:
    content = "<tag>first</tag> <tag>second</tag>"
    result = extract_xml_tag(content, "tag")
    assert result == "first"


def test_extract_xml_tag_empty_content() -> None:
    content = "<empty></empty>"
    result = extract_xml_tag(content, "empty")
    assert result == ""


def test_extract_xml_tag_nested_not_supported() -> None:
    # Non-greedy matching means nested tags don't work as expected
    content = "<outer><inner>content</inner></outer>"
    result = extract_xml_tag(content, "outer")
    assert result == "<inner>content</inner>"
