"""Verifier for doc-001: Text Formatting."""

import re
from pathlib import Path

import pytest


@pytest.fixture
def workspace(request):
    return Path(request.config.getoption("--workspace"))


@pytest.fixture
def formatted(workspace):
    path = workspace / "formatted.txt"
    assert path.exists(), "formatted.txt not found"
    return path.read_text()


def test_output_file_exists(workspace):
    assert (workspace / "formatted.txt").exists()


def test_no_line_exceeds_80_chars(formatted):
    for i, line in enumerate(formatted.splitlines(), 1):
        assert len(line) <= 80, f"Line {i} has {len(line)} chars: '{line}'"


def test_no_trailing_whitespace(formatted):
    for i, line in enumerate(formatted.splitlines(), 1):
        assert line == line.rstrip(), f"Line {i} has trailing whitespace"


def test_no_multiple_spaces_in_content(formatted):
    for i, line in enumerate(formatted.splitlines(), 1):
        content = line.lstrip()
        if content:
            assert "  " not in content, f"Line {i} has multiple consecutive spaces: '{line}'"


def test_space_after_periods(formatted):
    """Periods followed by a letter should have a space between."""
    for line in formatted.splitlines():
        matches = re.findall(r'\.[A-Za-z]', line)
        assert not matches, f"Missing space after period: {matches}"


def test_no_space_before_commas(formatted):
    for line in formatted.splitlines():
        assert " ," not in line, f"Space before comma found in: '{line}'"


def test_no_space_before_periods(formatted):
    for line in formatted.splitlines():
        assert " ." not in line, f"Space before period found in: '{line}'"


def test_indented_lines_preserved(formatted):
    """Lines that were intentionally indented should still have 2-space indent."""
    indented = [l for l in formatted.splitlines() if l.startswith("  ")]
    assert len(indented) >= 3, "Should have indented lines preserved"


def test_all_content_preserved(formatted):
    text = formatted.lower()
    assert "formatting issues" in text
    assert "normalize whitespace" in text
    assert "punctuation marks" in text
    assert "intentional indentation" in text


def test_no_space_before_colons(formatted):
    for line in formatted.splitlines():
        assert " :" not in line, f"Space before colon found in: '{line}'"
