"""Render skills to Cursor rules format.

Creates .cursor/rules/buildlog-rules.mdc with YAML frontmatter and
Markdown body containing learned rules.
"""

from __future__ import annotations

from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING

from buildlog.render.tracking import get_promoted_ids, track_promoted

if TYPE_CHECKING:
    from buildlog.skills import Skill


class CursorRenderer:
    """Creates .cursor/rules/buildlog-rules.mdc for Cursor IDE."""

    def __init__(self, path: Path | None = None, tracking_path: Path | None = None):
        """Initialize renderer.

        Args:
            path: Path to .mdc rules file. Defaults to .cursor/rules/buildlog-rules.mdc.
            tracking_path: Path to promoted.json tracking file.
                Defaults to .buildlog/promoted.json.
        """
        self.path = path or Path(".cursor/rules/buildlog-rules.mdc")
        self.tracking_path = tracking_path or Path(".buildlog/promoted.json")

    def render(self, skills: list[Skill]) -> str:
        """Render skills to Cursor .mdc rules file.

        Overwrites the file with all promoted skills (not append-only) since
        Cursor reads the entire file on each invocation.

        Args:
            skills: List of skills to render.

        Returns:
            Confirmation message.
        """
        if not skills:
            return "No skills to promote"

        # Filter out already-promoted skills
        already_promoted = get_promoted_ids(self.tracking_path)
        new_skills = [s for s in skills if s.id not in already_promoted]

        if not new_skills:
            return f"All {len(skills)} skills already promoted"

        # Group by category
        by_category: dict[str, list[Skill]] = {}
        for skill in new_skills:
            by_category.setdefault(skill.category, []).append(skill)

        category_titles = {
            "architectural": "Architectural",
            "workflow": "Workflow",
            "tool_usage": "Tool Usage",
            "domain_knowledge": "Domain Knowledge",
        }

        # Build MDC content with YAML frontmatter
        lines = [
            "---",
            "description: Buildlog-learned rules for code quality",
            "alwaysApply: true",
            "---",
            "",
            "# Learned Rules",
            "",
            f"*Auto-generated by buildlog on {datetime.now().strftime('%Y-%m-%d')}*",
            "",
        ]

        for category, cat_skills in by_category.items():
            title = category_titles.get(category, category.replace("_", " ").title())
            lines.append(f"## {title}")
            lines.append("")
            for skill in cat_skills:
                conf = skill.confidence
                freq = skill.frequency
                lines.append(
                    f"- **{skill.rule}** (confidence: {conf}, frequency: {freq})"
                )
            lines.append("")

        content = "\n".join(lines)

        # Write file
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.path.write_text(content)

        # Track promoted skill IDs
        track_promoted(new_skills, self.tracking_path)

        skipped = len(skills) - len(new_skills)
        msg = f"Wrote {len(new_skills)} rules to {self.path}"
        if skipped > 0:
            msg += f" ({skipped} already promoted, skipped)"
        return msg
