"""Apply suggestions directly to an AGENTS.md file."""

from datetime import date
from pathlib import Path
from typing import List
from ..models import RuleSuggestion

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


def apply_to_file(
    suggestions: List[RuleSuggestion],
    agents_file: str,
    yes: bool = False,
    echo=print,
) -> bool:
    """Append suggestions to an AGENTS.md file.

    Returns True if file was modified, False if skipped.
    """
    path = Path(agents_file)
    today = date.today().isoformat()

    if path.exists():
        existing = path.read_text(encoding="utf-8")
    else:
        existing = ""

    # Build the block to append
    lines_to_add = [f"\n\n{_LEARNED_SECTION}\n"]
    lines_to_add.append(f"<!-- auto-generated by agentreflect on {today} -->\n\n")
    for suggestion in suggestions:
        lines_to_add.append(f"{suggestion.as_markdown_item()}\n")

    block = "".join(lines_to_add)

    # Preview
    echo(f"\nWill append to {agents_file}:")
    echo("---")
    echo(block.strip())
    echo("---")

    if not yes:
        response = input("\nApply? [y/N] ").strip().lower()
        if response not in ("y", "yes"):
            echo("Skipped.")
            return False

    # Write to file
    with open(path, "a", encoding="utf-8") as f:
        f.write(block)

    echo(f"\nApplied {len(suggestions)} suggestions to {agents_file}")
    return True
