"""GitHub Copilot instructions template (.github/copilot-instructions.md)."""

from __future__ import annotations

from datetime import datetime, timezone

MARKER_START = "<!-- chowkidar:start -->"
MARKER_END = "<!-- chowkidar:end -->"


def generate_copilot_section(deprecations: list[dict]) -> str:
    """Generate the Chowkidar section for copilot-instructions.md."""
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

    lines = [
        MARKER_START,
        "",
        "## Chowkidar — Model Deprecation Alerts",
        "",
        "The following LLM models in this project are deprecated or sunsetting.",
        "When modifying files that reference these models, update them to the replacements.",
        "",
    ]

    for dep in deprecations:
        file_short = dep.get("file", "").split("/")[-1]
        replacement = dep.get("replacement") or "check provider docs"
        days = dep.get("days_until", "?")
        sunset = dep.get("sunset_date", "unknown")

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

        lines.append(
            f"- `{dep.get('model', '?')}` in `{file_short}` (`{dep.get('variable', '?')}`): "
            f"Sunset {sunset}{urgency}. Use `{replacement}` instead."
        )

    lines.extend([
        "",
        f"*Auto-generated by Chowkidar on {now}. Do not edit this section manually.*",
        "",
        MARKER_END,
    ])

    return "\n".join(lines)


def inject_into_copilot_file(existing_content: str, new_section: str) -> str:
    """Insert or replace the Chowkidar section in copilot-instructions.md."""
    if MARKER_START in existing_content:
        before = existing_content.split(MARKER_START)[0].rstrip()
        after_parts = existing_content.split(MARKER_END)
        after = after_parts[1].lstrip() if len(after_parts) > 1 else ""
        return f"{before}\n\n{new_section}\n\n{after}".strip() + "\n"
    else:
        if existing_content.strip():
            return f"{existing_content.rstrip()}\n\n{new_section}\n"
        return new_section + "\n"
