"""Mint a new MCPSigningKey for per-turn JWTs.

The secret is generated locally, printed once, and stored hex-encoded.
Distribute the printed secret to the issuer (Daedalus) — after this
command exits, the database row is the only copy on the Mnemosyne
side, but copying the secret out of the row is allowed (admin model
exposes it). Treat it like any other shared secret.

Use ``--retire-other`` to flip every other key to ``is_active=False``
in the same transaction (typical rotation flow). Without it, the new
key joins the active set and old keys keep validating until they are
retired explicitly.
"""

import secrets

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

from mcp_server.models import MCPSigningKey


class Command(BaseCommand):
    help = "Generate a new HMAC signing key for per-turn JWTs and print it once."

    def add_arguments(self, parser):
        parser.add_argument(
            "--kid",
            required=True,
            help="Key ID (short, stable string — e.g. 'daedalus-1').",
        )
        parser.add_argument(
            "--note",
            default="",
            help="Optional note (e.g. 'rotated 2026-05-03 after staging incident').",
        )
        parser.add_argument(
            "--retire-other",
            action="store_true",
            help=(
                "Mark every other MCPSigningKey row inactive in the same "
                "transaction. Use during rotation."
            ),
        )

    @transaction.atomic
    def handle(self, *args, **options):
        kid = options["kid"]
        if MCPSigningKey.objects.filter(kid=kid).exists():
            raise CommandError(f"kid {kid!r} already exists; choose a unique value.")

        # 256-bit secret, hex-encoded for portability.
        secret = secrets.token_hex(32)

        if options["retire_other"]:
            from django.utils import timezone
            MCPSigningKey.objects.filter(is_active=True).update(
                is_active=False, retired_at=timezone.now()
            )

        key = MCPSigningKey.objects.create(
            kid=kid, secret_hex=secret, is_active=True, note=options["note"]
        )

        self.stdout.write(self.style.SUCCESS("MCP signing key created"))
        self.stdout.write(f"  kid:    {key.kid}")
        self.stdout.write(f"  active: {key.is_active}")
        if options["retire_other"]:
            self.stdout.write("  (other active keys retired)")
        self.stdout.write(self.style.WARNING("  Secret (256-bit hex — share with Daedalus):"))
        self.stdout.write(f"  {secret}")
