"""
cursor_generator.py — Generate Cursor-compatible .mdc rules files from Mneme decisions.
"""

from __future__ import annotations

from mneme.decision_retriever import ScoredDecision


def generate_mdc(
    scored: list[ScoredDecision],
    query: str,
    memory_path: str,
    top: int = 3,
    timestamp: str = "",
) -> str:
    """Return the contents of a Cursor .mdc rules file for the given decisions.

    Filters to top-N scored decisions (score > 0). Returns a file with YAML
    frontmatter, a warning header, and one section per decision containing its
    constraints and anti-patterns.
    """
    kept: list[ScoredDecision] = []
    seen: set[str] = set()
    for s in scored:
        if s.score <= 0:
            continue
        if s.decision.id in seen:
            continue
        seen.add(s.decision.id)
        kept.append(s)
        if len(kept) >= top:
            break

    lines: list[str] = [
        "---",
        f'description: "Mneme decisions for: {query}"',
        'globs: "**/*"',
        "alwaysApply: false",
        "---",
        "",
        "# Mneme Project Memory",
        "",
        "> ⚠️ Generated by Mneme — do not edit manually.",
        f"> Source: {memory_path}",
        f"> Query: {query}",
        f"> Generated: {timestamp}",
        "",
    ]

    if not kept:
        lines.append("_(no decisions matched this query)_")
        return "\n".join(lines)

    lines.append("## Decisions")
    lines.append("")

    for s in kept:
        d = s.decision
        lines.append(f"### [{d.id}] {d.decision}")
        lines.append("")
        if d.rationale:
            lines.append(f"**Why:** {d.rationale}")
            lines.append("")
        if d.scope:
            lines.append(f"**Scope:** {', '.join(d.scope)}")
            lines.append("")
        if d.constraints:
            lines.append("**Constraints:**")
            for c in d.constraints:
                lines.append(f"- {c}")
            lines.append("")
        if d.anti_patterns:
            lines.append("**Avoid:**")
            for a in d.anti_patterns:
                lines.append(f"- {a}")
            lines.append("")

    return "\n".join(lines)
