"""Cursor IDE rule file template (.cursor/rules/chowkidar-alerts.mdc)."""

from __future__ import annotations

from datetime import datetime, timezone


def generate_cursor_rules(deprecations: list[dict]) -> str:
    """Generate a .mdc rules file for Cursor."""
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

    globs = '["**/.env*", "**/config.*", "**/settings.*", "**/constants.*", "**/*.py", "**/*.js", "**/*.ts"]'
    header = f"""---
description: "Chowkidar — LLM model deprecation alerts (auto-generated)"
globs: {globs}
alwaysApply: false
---

## Model Deprecation Alerts (auto-generated by Chowkidar)

The following models used in this project are deprecated or sunsetting soon.
**When editing any file containing these model strings, update them to the recommended replacements.**

"""

    table = _build_table(deprecations)

    footer = f"""
---
*Last updated: {now} by [Chowkidar](https://github.com/chowkidar)*
*Do not edit this file manually — it is regenerated automatically.*
"""

    return header + table + footer


def _build_table(deprecations: list[dict]) -> str:
    lines = ["| Variable | File | Current Model | Sunset Date | Replacement | Confidence | Breaking? |"]
    lines.append("|---|---|---|---|---|---|---|")

    for dep in deprecations:
        file_short = dep.get("file", "").split("/")[-1]
        replacement = dep.get("replacement") or "check provider docs"
        confidence = dep.get("replacement_confidence", "medium")
        breaking = "Yes" if dep.get("breaking_changes") else "No"
        days = dep.get("days_until", "?")
        sunset = dep.get("sunset_date", "unknown")

        if isinstance(days, int) and days <= 0:
            sunset = f"**{sunset} (PASSED)**"
        elif isinstance(days, int) and days <= 7:
            sunset = f"**{sunset} ({days}d left)**"
        elif isinstance(days, int):
            sunset = f"{sunset} ({days}d left)"

        lines.append(
            f"| `{dep.get('variable', '?')}` "
            f"| `{file_short}` "
            f"| `{dep.get('model', '?')}` "
            f"| {sunset} "
            f"| `{replacement}` "
            f"| {confidence} "
            f"| {breaking} |"
        )

    return "\n".join(lines)
