import pytest

from a11yviz import check_headings


def test_clean_hierarchy(tmp_path):
    f = tmp_path / "doc.md"
    f.write_text("# Title\n## Section\n### Sub\n## Another\n### Sub\n")
    assert check_headings(f) == []


def test_level_skip_detected(tmp_path):
    f = tmp_path / "doc.md"
    f.write_text("# Title\n## Section\n#### Skipped\n")
    res = check_headings(f)
    assert len(res) == 1
    assert res[0]["level"] == 4
    assert "h2 to h4" in res[0]["issue"]


def test_code_fence_hashes_ignored(tmp_path):
    f = tmp_path / "doc.qmd"
    f.write_text(
        "# Title\n```r\n## not a heading\n#### also not\n```\n## Real section\n"
    )
    assert check_headings(f) == []


def test_missing_file_raises(tmp_path):
    with pytest.raises(FileNotFoundError):
        check_headings(tmp_path / "missing.md")


def test_html_skip(tmp_path):
    f = tmp_path / "doc.html"
    f.write_text("<h1>Title</h1><h2>Section</h2><h4>Skipped</h4>")
    res = check_headings(f)
    assert len(res) == 1
    assert "h2 to h4" in res[0]["issue"]


def test_yaml_frontmatter_skipped(tmp_path):
    f = tmp_path / "doc.qmd"
    f.write_text(
        "---\ntitle: \"Some study\"\nformat: html\n---\n\n# Real title\n## Real section\n"
    )
    assert check_headings(f) == []


def test_empty_heading_flagged(tmp_path):
    f = tmp_path / "doc.md"
    f.write_text("# Title\n##\n## Real section\n")
    res = check_headings(f)
    issues = {r["issue"] for r in res}
    assert "Empty heading" in issues


def test_short_heading_flagged(tmp_path):
    f = tmp_path / "doc.md"
    f.write_text("# Title\n## A\n## Real section\n")
    res = check_headings(f, min_chars=3)
    assert any("under 3 chars" in r["issue"] for r in res)


def test_min_chars_configurable(tmp_path):
    f = tmp_path / "doc.md"
    f.write_text("# Title\n## Hi\n")
    assert check_headings(f, min_chars=2) == []
    assert any("under 5 chars" in r["issue"] for r in check_headings(f, min_chars=5))
