"""Issue an API key from the CLI; the secret is printed once."""

from typing import Any

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

from snapfile.integration.keys import DEFAULT_SCOPES, issue_key
from snapfile.projects.models import Project


class Command(BaseCommand):
    help = "Issue an API key: snapfile_key_create <project-slug> [--name] [--scopes a,b] [--env live|test]"

    def add_arguments(self, parser: Any) -> None:
        parser.add_argument("slug")
        parser.add_argument("--name", default="cli key")
        parser.add_argument("--scopes", default=",".join(DEFAULT_SCOPES))
        parser.add_argument("--env", default="live", choices=["live", "test"])
        parser.add_argument("--require-signature", action="store_true")

    def handle(self, *args: Any, **opts: Any) -> None:
        p = Project.objects.filter(slug=opts["slug"]).first()
        if p is None:
            raise CommandError("project not found")
        issued = issue_key(
            p, opts["name"], opts["scopes"].split(","), env=opts["env"], require_signature=opts["require_signature"]
        )
        self.stdout.write(issued.secret)
        if issued.hmac_secret:
            self.stdout.write(f"hmac secret: {issued.hmac_secret}")
