"""Tests for output formatters."""

import os
import tempfile
from pathlib import Path

import pytest
from agentreflect.models import FailureRecord, RuleSuggestion
from agentreflect.output.markdown_formatter import format_markdown
from agentreflect.output.diff_formatter import format_diff
from agentreflect.output.apply import apply_to_file


def make_suggestions(n=2):
    return [
        RuleSuggestion(category="test", text=f"Rule {i}", confidence=0.9, source="test")
        for i in range(n)
    ]

def make_records(n=1):
    return [FailureRecord(type="AttributeError", message=f"msg {i}") for i in range(n)]


class TestMarkdownFormatter:
    def test_contains_date_header(self):
        output = format_markdown(make_suggestions(), make_records())
        assert "## agentreflect suggestions" in output

    def test_contains_suggestion_items(self):
        suggestions = make_suggestions(3)
        output = format_markdown(suggestions, make_records())
        assert "- [ ] Rule 0" in output
        assert "- [ ] Rule 1" in output

    def test_contains_source_label(self):
        output = format_markdown(make_suggestions(), make_records(), source_label="pytest failures")
        assert "pytest failures" in output

    def test_empty_suggestions_shows_message(self):
        output = format_markdown([], make_records())
        assert "No suggestions" in output

    def test_summary_line(self):
        records = make_records(3)
        suggestions = make_suggestions(2)
        output = format_markdown(suggestions, records)
        assert "3 failures analyzed" in output
        assert "2 suggestions generated" in output


class TestDiffFormatter:
    def test_diff_contains_plus_lines(self):
        suggestions = make_suggestions(2)
        output = format_diff(suggestions, "AGENTS.md")
        assert any(line.startswith("+") for line in output.splitlines())

    def test_diff_contains_file_headers(self):
        output = format_diff(make_suggestions(), "AGENTS.md")
        assert "--- AGENTS.md" in output
        assert "+++ AGENTS.md" in output

    def test_diff_contains_section_header(self):
        output = format_diff(make_suggestions(), "AGENTS.md")
        assert "Learned Rules" in output

    def test_diff_contains_rule_text(self):
        suggestions = [RuleSuggestion(category="x", text="Check None before access", confidence=0.9)]
        output = format_diff(suggestions, "AGENTS.md")
        assert "Check None before access" in output

    def test_diff_with_existing_content(self):
        output = format_diff(make_suggestions(), "AGENTS.md", existing_content="# Existing\n\n- rule 1\n")
        assert "--- AGENTS.md" in output


class TestApplyMode:
    def test_creates_section_in_new_file(self, tmp_path):
        agents_file = str(tmp_path / "AGENTS.md")
        # File doesn't exist yet
        suggestions = [RuleSuggestion(category="x", text="Always check None", confidence=0.9)]
        messages = []
        apply_to_file(suggestions, agents_file, yes=True, echo=messages.append)
        content = Path(agents_file).read_text()
        assert "Learned Rules" in content
        assert "Always check None" in content

    def test_appends_to_existing_file(self, tmp_path):
        agents_file = tmp_path / "AGENTS.md"
        agents_file.write_text("# Existing Rules\n\n- rule 1\n")
        suggestions = [RuleSuggestion(category="x", text="New rule here", confidence=0.9)]
        apply_to_file(suggestions, str(agents_file), yes=True, echo=lambda x: None)
        content = agents_file.read_text()
        assert "Existing Rules" in content
        assert "New rule here" in content

    def test_apply_returns_true_on_success(self, tmp_path):
        agents_file = str(tmp_path / "AGENTS.md")
        suggestions = make_suggestions(1)
        result = apply_to_file(suggestions, agents_file, yes=True, echo=lambda x: None)
        assert result is True

    def test_apply_includes_timestamp(self, tmp_path):
        agents_file = str(tmp_path / "AGENTS.md")
        suggestions = make_suggestions(1)
        apply_to_file(suggestions, agents_file, yes=True, echo=lambda x: None)
        content = Path(agents_file).read_text()
        # Should contain a date in the comment
        import re
        assert re.search(r"\d{4}-\d{2}-\d{2}", content)
