"""
Generate Claude Code routing snippets from the downsize analyzer.

Output shape — a `.claude/settings.json`-shaped fragment under a
`tokenjam.routing_recommendations` namespace, with honest-framing
comments baked in as JSON `//` comments (Claude Code's settings.json
parser tolerates them; standard JSON parsers do not, so the file is
served as JSONC).

The snippet is written to a file the user can read and merge into their
config manually. No `--apply` flag — Claude Code doesn't currently honor
`tokenjam.routing_recommendations` keys, so writing them automatically
would change nothing in Claude Code's behavior and erode user trust.

Plan-tier-aware:
  - API users: rules carry `estimated_savings_usd_month`.
  - Subscription users: rules carry `estimated_tokens_freed` (per the
    v1.1 honest-output spec — never quote dollar savings against a
    flat-rate plan).
  - Unknown plan-tier: rules carry neither figure; the snippet header
    comment points the user at `tj onboard --reconfigure`.
"""
from __future__ import annotations

from datetime import datetime, timezone

from tokenjam.core.optimize.types import DowngradeFinding


def _comment_block(lines: list[str]) -> str:
    # 6-space indent so the comment block aligns with the surrounding
    # "routing_recommendations" object body (#71 finding 4).
    return "\n".join(f"      // {line}" for line in lines)


def render_claude_code_snippet(
    *,
    downgrade: DowngradeFinding | None,
    pricing_mode: str,
    plan_tier: str,
    agent_id: str | None = None,
) -> str:
    """
    Return a JSONC string ready to write to disk.

    Embeds the routing recommendations under `tokenjam.routing_recommendations`
    with mandatory honest-framing comments at the top of the section.
    """
    timestamp = datetime.now(tz=timezone.utc).isoformat()

    rules_blocks: list[str] = []
    if downgrade is not None and downgrade.suggestions:
        for original_model, alt_model in sorted(downgrade.suggestions.items()):
            # Pick the figure that matches the user's pricing mode.
            if pricing_mode == "api":
                figure_line = (
                    f'      "estimated_savings_usd_month": '
                    f'{downgrade.monthly_savings_usd}'
                )
            elif pricing_mode in {"subscription", "local"}:
                figure_line = (
                    f'      "estimated_tokens_freed": '
                    f'{downgrade.monthly_tokens_in_candidates}'
                )
            else:
                figure_line = (
                    '      "note": "configure plan tier with '
                    '`tj onboard --reconfigure` to see savings projections"'
                )

            rules_blocks.append(
                "    {\n"
                f'      "match": {{"original_model": "{original_model}"}},\n'
                f'      "model": "{alt_model}",\n'
                f'      "confidence": "structural",\n'
                f"{figure_line}\n"
                "    }"
            )

    rules_array = ",\n".join(rules_blocks) if rules_blocks else ""

    # Mandatory caveat comments. Always present, in every export, regardless
    # of plan tier — the strategy doc's honesty discipline §4.5 is hard rule.
    caveat = [
        "⚠ STRUCTURAL HEURISTIC ONLY: review before applying.",
        "",
        "These recommendations come from session structural patterns,",
        "not validated quality equivalence. Each rule names a class of",
        "sessions and suggests a cheaper model. Test on a few real",
        "sessions before trusting broadly.",
        "",
        "TokenJam does not enforce these rules. You apply them by",
        "configuring your routing layer (Claude Code settings, LiteLLM",
        "config, framework code) according to your judgment.",
        "",
        "See https://tokenjam.dev/products/downsize for details.",
    ]
    scope = f"agent_id={agent_id}" if agent_id else "all agents"
    header = [
        "Generated by tj optimize export-config --target claude-code",
        f"Generated at: {timestamp}",
        f"Scope: {scope}",
        f"Plan tier: {plan_tier} ({pricing_mode} pricing)",
    ]

    return (
        "{\n"
        '  "tokenjam": {\n'
        '    "routing_recommendations": {\n'
        f"{_comment_block(header)}\n"
        "      //\n"
        f"{_comment_block(caveat)}\n"
        f'      "generated_at": "{timestamp}",\n'
        f'      "plan_tier": "{plan_tier}",\n'
        f'      "pricing_mode": "{pricing_mode}",\n'
        '      "rules": [\n'
        f"{rules_array}\n"
        "      ]\n"
        "    }\n"
        "  }\n"
        "}\n"
    )
