"""Diff output formatter."""

from datetime import date
from typing import List, Optional
from ..models import RuleSuggestion


_LEARNED_SECTION = "## Learned Rules (auto-generated by agentreflect)"


def format_diff(
    suggestions: List[RuleSuggestion],
    agents_file: str = "AGENTS.md",
    existing_content: Optional[str] = None,
) -> str:
    """Format suggestions as a unified diff against AGENTS.md."""
    today = date.today().isoformat()

    # Build lines to add
    new_lines = [
        "",
        _LEARNED_SECTION,
        f"<!-- auto-generated by agentreflect on {today} -->",
        "",
    ]
    for suggestion in suggestions:
        new_lines.append(suggestion.as_markdown_item())
    new_lines.append("")

    if existing_content is None:
        # Generate diff against empty file
        old_lines = []
    else:
        old_lines = existing_content.splitlines()

    # Check if section already exists
    section_line = None
    for i, line in enumerate(old_lines):
        if line.strip() == _LEARNED_SECTION:
            section_line = i
            break

    if section_line is not None:
        insert_at = section_line + 1
    else:
        insert_at = len(old_lines)

    # Build diff output
    diff_lines = [
        f"--- {agents_file}",
        f"+++ {agents_file}",
        f"@@ -{insert_at},0 +{insert_at},{len(new_lines)} @@",
    ]
    for line in new_lines:
        diff_lines.append(f"+{line}")

    return "\n".join(diff_lines) + "\n"
