"""List item tests: the seven declared checks from FEATURE-List-Items.md, then block-tree and exact-output
tests for markers, content columns, empty items, start numbers, laziness and interruption.

The declared checks are transcribed first, with their assertions unchanged. The rest act on the
block tree returned by `parse_lines` and on the exact stdout bytes, which is the state handed back.
"""

import subprocess
from pathlib import Path

import pytest

from mdparser.blocks import DEFAULT_REGISTRY, LIST_ITEM, PARAGRAPH, Block, parse_lines


def run_commonmark(project_root: Path, source: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        [str(project_root / "commonmark")],
        input=source,
        capture_output=True,
        text=True,
        cwd=project_root,
        check=False,
    )


def kinds(block: Block) -> list[str]:
    """Names of the child block types of `block`, in order."""
    return [child.kind.name for child in block.children]


def paragraph_texts(block: Block) -> list[str]:
    """Raw content of every paragraph under `block`, in document order."""
    texts: list[str] = []
    for child in block.children:
        if child.kind is PARAGRAPH:
            texts.append(child.content)
        texts.extend(paragraph_texts(child))
    return texts


def only_item(lines: list[str]) -> Block:
    """The single list item at the top of the document built from `lines`."""
    root = parse_lines(lines)
    assert kinds(root) == ["list_item"]
    return root.children[0]


# --- Declared acceptance checks (transcribed from FEATURE-List-Items.md) ---


def test_items_bullet_items(project_root: Path) -> None:
    """Each bullet marker line starts one li element, and consecutive items of one marker form one ul."""
    items = ["first", "second", "third"]
    source = "".join("- " + text + "\n" for text in items)
    result = subprocess.run([str(project_root / "commonmark")], input=source, capture_output=True, text=True)
    print(result.stdout)
    assert result.returncode == 0
    assert result.stdout.count("<li>") == len(items)
    assert result.stdout.count("<ul>") == 1
    for text in items:
        assert text in result.stdout


def test_items_ordered_start_number(project_root: Path) -> None:
    """An ordered list takes its start number from the first item, and ten digits is not a marker."""
    number = 123456789
    good = subprocess.run([str(project_root / "commonmark")], input=str(number) + ". ok\n", capture_output=True, text=True)
    bad = subprocess.run([str(project_root / "commonmark")], input=str(number) + "0. not ok\n", capture_output=True, text=True)
    print(good.stdout)
    print(bad.stdout)
    assert good.returncode == 0
    assert bad.returncode == 0
    assert ('start="' + str(number) + '"') in good.stdout
    assert bad.stdout.count("<ol") == 0


def test_items_continuation_paragraph(project_root: Path) -> None:
    """A continuation paragraph indented to the content column joins the item, giving a loose item with two paragraphs."""
    result = subprocess.run([str(project_root / "commonmark")], input="- one\n\n  two\n", capture_output=True, text=True)
    print(result.stdout)
    assert result.returncode == 0
    assert result.stdout.count("<li>") == 1
    assert result.stdout.count("<p>") == 2


def test_items_insufficient_indent_ends_item(project_root: Path) -> None:
    """A paragraph indented less than the content column is outside the item."""
    result = subprocess.run([str(project_root / "commonmark")], input="- one\n\n two\n", capture_output=True, text=True)
    print(result.stdout)
    assert result.returncode == 0
    assert result.stdout.count("<li>") == 1
    assert result.stdout.count("<p>") == 1


def test_items_empty_items(project_root: Path) -> None:
    """Empty items are allowed in the middle of a list, but an empty item cannot interrupt a paragraph."""
    middle = subprocess.run([str(project_root / "commonmark")], input="- foo\n-\n- bar\n", capture_output=True, text=True)
    interrupt = subprocess.run([str(project_root / "commonmark")], input="foo\n*\n", capture_output=True, text=True)
    print(middle.stdout)
    print(interrupt.stdout)
    assert middle.returncode == 0
    assert interrupt.returncode == 0
    assert middle.stdout.count("<li>") == 2 + 1
    assert interrupt.stdout.count("<li>") == 0


def test_items_nested_and_code(project_root: Path) -> None:
    """A sublist indented to the content column nests, and a code block six spaces in is code inside the item."""
    nested = subprocess.run([str(project_root / "commonmark")], input="- foo\n  - bar\n", capture_output=True, text=True)
    code = subprocess.run([str(project_root / "commonmark")], input="- foo\n\n      bar\n", capture_output=True, text=True)
    print(nested.stdout)
    print(code.stdout)
    assert nested.returncode == 0
    assert code.returncode == 0
    assert nested.stdout.count("<ul>") == 2
    assert code.stdout.count("<pre>") == 1


def test_items_four_spaces_is_code(project_root: Path) -> None:
    """A marker indented four spaces is code, not a list item."""
    result = subprocess.run([str(project_root / "commonmark")], input="    1.  A paragraph\n", capture_output=True, text=True)
    print(result.stdout)
    assert result.returncode == 0
    assert result.stdout.count("<ol") == 0
    assert result.stdout.count("<pre>") == 1


# --- Markers ---


@pytest.mark.parametrize("bullet", ["-", "+", "*"])
def test_each_bullet_character_starts_an_item(bullet: str) -> None:
    item = only_item([f"{bullet} foo"])
    assert item.item is not None
    assert item.item.ordered is False
    assert item.item.delimiter == bullet


@pytest.mark.parametrize("delimiter", [".", ")"])
def test_ordered_marker_records_its_number_and_delimiter(delimiter: str) -> None:
    item = only_item([f"3{delimiter} foo"])
    assert item.item is not None
    assert item.item.ordered is True
    assert item.item.start == 3
    assert item.item.delimiter == delimiter


def test_nine_digit_number_is_a_marker() -> None:
    item = only_item(["123456789. foo"])
    assert item.item is not None
    assert item.item.start == 123456789


def test_ten_digit_number_is_not_a_marker() -> None:
    root = parse_lines(["1234567890. foo"])
    assert kinds(root) == ["paragraph"]


@pytest.mark.parametrize("line", ["-foo", "+bar", "1.foo", "2)baz"])
def test_marker_must_be_followed_by_space_or_tab(line: str) -> None:
    root = parse_lines([line])
    assert kinds(root) == ["paragraph"]


def test_marker_at_end_of_line_is_an_empty_item() -> None:
    item = only_item(["-"])
    assert item.children == []


def test_leading_zeros_do_not_change_the_start_number() -> None:
    item = only_item(["007. foo"])
    assert item.item is not None
    assert item.item.start == 7


def test_marker_may_be_indented_three_spaces() -> None:
    item = only_item(["   - foo"])
    assert item.item is not None


def test_marker_indented_four_spaces_is_indented_code() -> None:
    root = parse_lines(["    - foo"])
    assert kinds(root) == ["indented_code"]


def test_thematic_break_takes_precedence_over_an_item() -> None:
    root = parse_lines(["* * *"])
    assert kinds(root) == ["thematic_break"]


def test_item_is_a_container_for_blocks() -> None:
    assert LIST_ITEM.is_container is True


def test_default_registry_includes_list_item() -> None:
    assert LIST_ITEM in DEFAULT_REGISTRY.starts()


# --- Content column ---


def test_content_column_is_marker_plus_one_space() -> None:
    item = only_item(["- foo"])
    assert item.item is not None
    assert item.item.content_column == 2


def test_content_column_takes_spaces_up_to_four() -> None:
    item = only_item(["-   foo"])
    assert item.item is not None
    assert item.item.content_column == 4


def test_five_spaces_after_marker_make_the_content_code() -> None:
    item = only_item(["-     foo"])
    assert item.item is not None
    assert item.item.content_column == 2
    assert kinds(item) == ["indented_code"]


def test_blank_start_content_column_is_marker_plus_one() -> None:
    item = only_item(["1."])
    assert item.item is not None
    assert item.item.content_column == 3


def test_content_column_is_absolute_for_a_nested_item() -> None:
    outer = only_item(["- - foo"])
    inner = outer.children[0]
    assert inner.item is not None
    assert inner.item.content_column == 4


def test_tab_after_marker_counts_to_the_next_tab_stop() -> None:
    item = only_item(["-\tfoo"])
    assert item.item is not None
    assert item.item.content_column == 4


# --- Empty items and the blank line ---


def test_empty_item_has_no_children() -> None:
    item = only_item(["-"])
    assert item.children == []


def test_empty_item_takes_an_indented_continuation_line() -> None:
    item = only_item(["-", "  foo"])
    assert kinds(item) == ["paragraph"]
    assert paragraph_texts(item) == ["foo"]


def test_blank_line_after_an_empty_item_ends_it() -> None:
    root = parse_lines(["-", "", "  foo"])
    assert kinds(root) == ["list_item", "paragraph"]
    assert root.children[0].children == []
    assert root.children[1].content == "foo"


def test_blank_line_keeps_an_item_with_content_open() -> None:
    item = only_item(["- foo", "", "  bar"])
    assert paragraph_texts(item) == ["foo", "bar"]


def test_blank_lines_inside_an_item_with_content_do_not_end_it() -> None:
    root = parse_lines(["- foo", "", "", "  bar"])
    assert kinds(root) == ["list_item"]
    assert paragraph_texts(root) == ["foo", "bar"]


# --- Indentation and nesting ---


def test_nested_item_is_inside_its_parent_at_the_content_column() -> None:
    item = only_item(["- foo", "  - bar"])
    assert kinds(item) == ["paragraph", "list_item"]


def test_paragraph_indented_less_than_the_content_column_is_outside_the_item() -> None:
    root = parse_lines(["- one", "", " two"])
    assert kinds(root) == ["list_item", "paragraph"]
    assert paragraph_texts(root.children[0]) == ["one"]
    assert root.children[1].content == "two"


def test_indented_code_inside_an_item_needs_six_spaces() -> None:
    item = only_item(["- foo", "", "      bar"])
    assert kinds(item) == ["paragraph", "indented_code"]


def test_item_inside_a_block_quote() -> None:
    root = parse_lines(["> - foo"])
    assert kinds(root) == ["block_quote"]
    assert kinds(root.children[0]) == ["list_item"]


# --- Laziness and interruption ---


def test_lazy_line_joins_the_item_paragraph() -> None:
    root = parse_lines(["- foo", "bar"])
    assert kinds(root) == ["list_item"]
    assert paragraph_texts(root) == ["foo\nbar"]


def test_unindented_text_after_a_blank_line_is_not_lazy() -> None:
    root = parse_lines(["- foo", "", "bar"])
    assert kinds(root) == ["list_item", "paragraph"]
    assert paragraph_texts(root.children[0]) == ["foo"]


def test_bullet_item_interrupts_a_paragraph() -> None:
    root = parse_lines(["foo", "- bar"])
    assert kinds(root) == ["paragraph", "list_item"]


def test_ordered_item_starting_at_one_interrupts_a_paragraph() -> None:
    root = parse_lines(["foo", "1. bar"])
    assert kinds(root) == ["paragraph", "list_item"]


def test_ordered_item_not_starting_at_one_does_not_interrupt_a_paragraph() -> None:
    root = parse_lines(["foo", "2. bar"])
    assert kinds(root) == ["paragraph"]
    assert paragraph_texts(root) == ["foo\n2. bar"]


def test_empty_item_does_not_interrupt_a_paragraph() -> None:
    root = parse_lines(["foo", "*"])
    assert kinds(root) == ["paragraph"]
    assert paragraph_texts(root) == ["foo\n*"]


def test_empty_item_can_follow_an_item_without_a_blank_line() -> None:
    root = parse_lines(["- foo", "-", "- bar"])
    assert kinds(root) == ["list_item", "list_item", "list_item"]


def test_ordered_item_not_starting_at_one_may_start_after_an_item() -> None:
    root = parse_lines(["- foo", "2. bar"])
    assert kinds(root) == ["list_item", "list_item"]


def test_thematic_break_after_an_item_is_not_an_item() -> None:
    root = parse_lines(["- foo", "***"])
    assert kinds(root) == ["list_item", "thematic_break"]


def test_item_changes_when_the_marker_changes() -> None:
    root = parse_lines(["- a", "* b"])
    assert kinds(root) == ["list_item", "list_item"]
    assert [child.item.delimiter for child in root.children if child.item] == ["-", "*"]


# --- Exact output ---


def test_bullet_list_output_is_exact(project_root: Path) -> None:
    result = run_commonmark(project_root, "- foo\n- bar\n")
    assert result.stdout == "<ul>\n<li>foo</li>\n<li>bar</li>\n</ul>\n"


def test_ordered_list_output_is_exact(project_root: Path) -> None:
    result = run_commonmark(project_root, "1. foo\n2. bar\n")
    assert result.stdout == "<ol>\n<li>foo</li>\n<li>bar</li>\n</ol>\n"


def test_ordered_list_states_a_start_number_other_than_one(project_root: Path) -> None:
    result = run_commonmark(project_root, "3. a\n4. b\n")
    assert result.stdout == '<ol start="3">\n<li>a</li>\n<li>b</li>\n</ol>\n'


def test_zero_start_number_is_stated(project_root: Path) -> None:
    result = run_commonmark(project_root, "0. zero\n")
    assert result.stdout == '<ol start="0">\n<li>zero</li>\n</ol>\n'


def test_leading_zeros_render_the_number_without_them(project_root: Path) -> None:
    result = run_commonmark(project_root, "007. foo\n")
    assert result.stdout == '<ol start="7">\n<li>foo</li>\n</ol>\n'


def test_empty_item_renders_an_empty_li(project_root: Path) -> None:
    result = run_commonmark(project_root, "-\n")
    assert result.stdout == "<ul>\n<li></li>\n</ul>\n"


def test_lazy_continuation_renders_inside_the_tight_item(project_root: Path) -> None:
    result = run_commonmark(project_root, "- foo\nbar\n")
    assert result.stdout == "<ul>\n<li>foo\nbar</li>\n</ul>\n"


def test_blank_line_between_items_makes_the_list_loose(project_root: Path) -> None:
    result = run_commonmark(project_root, "- foo\n\n- bar\n")
    assert result.stdout == "<ul>\n<li>\n<p>foo</p>\n</li>\n<li>\n<p>bar</p>\n</li>\n</ul>\n"


def test_blank_line_inside_an_item_makes_that_list_loose(project_root: Path) -> None:
    result = run_commonmark(project_root, "- one\n\n  two\n")
    assert result.stdout == "<ul>\n<li>\n<p>one</p>\n<p>two</p>\n</li>\n</ul>\n"


def test_trailing_blank_line_leaves_the_list_tight(project_root: Path) -> None:
    result = run_commonmark(project_root, "- foo\n\n")
    assert result.stdout == "<ul>\n<li>foo</li>\n</ul>\n"


def test_nested_tight_list_output_is_exact(project_root: Path) -> None:
    result = run_commonmark(project_root, "- foo\n  - bar\n")
    assert result.stdout == "<ul>\n<li>foo\n<ul>\n<li>bar</li>\n</ul>\n</li>\n</ul>\n"


def test_five_spaces_after_marker_output_is_code_inside_the_item(project_root: Path) -> None:
    result = run_commonmark(project_root, "-     code\n")
    assert result.stdout == "<ul>\n<li><pre><code>code\n</code></pre>\n</li>\n</ul>\n"


def test_change_of_bullet_character_starts_a_new_list(project_root: Path) -> None:
    result = run_commonmark(project_root, "- a\n* b\n")
    assert result.stdout == "<ul>\n<li>a</li>\n</ul>\n<ul>\n<li>b</li>\n</ul>\n"


def test_change_of_ordered_delimiter_starts_a_new_list(project_root: Path) -> None:
    result = run_commonmark(project_root, "1. a\n1) b\n")
    assert result.stdout == "<ol>\n<li>a</li>\n</ol>\n<ol>\n<li>b</li>\n</ol>\n"


def test_paragraph_between_items_splits_the_list(project_root: Path) -> None:
    result = run_commonmark(project_root, "- a\n\nb\n\n- c\n")
    assert result.stdout == "<ul>\n<li>a</li>\n</ul>\n<p>b</p>\n<ul>\n<li>c</li>\n</ul>\n"


def test_thematic_break_between_items_is_outside_the_lists(project_root: Path) -> None:
    result = run_commonmark(project_root, "* Foo\n* * *\n* Bar\n")
    assert result.stdout == "<ul>\n<li>Foo</li>\n</ul>\n<hr />\n<ul>\n<li>Bar</li>\n</ul>\n"


def test_empty_input_renders_nothing(project_root: Path) -> None:
    result = run_commonmark(project_root, "")
    assert result.stdout == ""


def test_item_wraps_paragraph_text_in_li_without_p(project_root: Path) -> None:
    result = run_commonmark(project_root, "- foo\n  bar\n")
    assert "<p>" not in result.stdout
    assert result.stdout == "<ul>\n<li>foo\nbar</li>\n</ul>\n"
