import pytest

from srs2std.srs.structure import (
    SectionTitle,
    TableOfContents,
    build_toc_from_md,
    split_md_by_toc,
)


def test_section_title_trim_and_lower():
    section_title = SectionTitle(number=" 1.1.1\t", name=" Section Title ")
    assert section_title.number == "1.1.1"
    assert section_title.name == "Section title"
    assert section_title.to_str() == "### 1.1.1 Section title"


def test_section_title_validation():
    with pytest.raises(ValueError):
        SectionTitle(number="A", name="Section")
    with pytest.raises(ValueError):
        SectionTitle(number="1.", name="Section")
    with pytest.raises(ValueError):
        SectionTitle(number="1 1.1", name="Section")


def test_split_md_by_doc_values_full_sections():
    toc = TableOfContents(
        titles=[
            SectionTitle(number="1", name="One"),
            SectionTitle(number="1.1", name="One one"),
        ]
    )

    md_doc = """\
# 1 One
AAA

## 1.1 One one
BBB
CCC
"""

    expected_titles = [
        SectionTitle(number="1", name="One"),
        SectionTitle(number="1.1", name="One one"),
    ]
    expected_contents = [
        "AAA",
        "BBB\nCCC",
    ]
    actual_titles, actual_contents = split_md_by_toc(md_doc, toc)
    assert actual_titles == expected_titles
    assert actual_contents == expected_contents


def test_split_md_by_doc_values_when_falling():
    toc = TableOfContents(
        titles=[
            SectionTitle(number="1", name="One"),
            SectionTitle(number="1.1", name="One one"),
        ]
    )

    md_doc = """\
Ignored here.

## 1.1 One one
BBB
CCC
"""

    expected_titles = [
        SectionTitle(number="1.1", name="One one"),
    ]
    expected_contents = [
        "BBB\nCCC",
    ]
    actual_titles, actual_contents = split_md_by_toc(md_doc, toc)
    assert actual_titles == expected_titles
    assert actual_contents == expected_contents


def test_build_toc_from_md():
    md_doc = """\
# 1 One
AAA

## 1.1 One one
BBB
CCC

# 2 Two
DDD
"""
    expected = TableOfContents(
        titles=[
            SectionTitle(number="1", name="One"),
            SectionTitle(number="1.1", name="One one"),
            SectionTitle(number="2", name="Two"),
        ]
    )
    assert build_toc_from_md(md_doc) == expected


def test_build_toc_from_md_without_number():
    md_doc = """\
# 1 One
AAA

## One one
Ignored this header as it has no number.

# 2 Two
DDD
"""
    expected = TableOfContents(
        titles=[
            SectionTitle(number="1", name="One"),
            SectionTitle(number="2", name="Two"),
        ]
    )
    assert build_toc_from_md(md_doc) == expected
