"""Seed the demo project AGA with the published "Investment Proposal" template and an API key."""

from __future__ import annotations

from typing import Any

from django.conf import settings
from django.core.management.base import BaseCommand

from snapfile.auth_sso.sessions import issue_session
from snapfile.core import ids
from snapfile.projects.demo import seed


class Command(BaseCommand):
    help = "Create demo project 'aga' with a published Investment Proposal template and print an API key."

    def add_arguments(self, parser: Any) -> None:
        parser.add_argument("--slug", default="aga")
        parser.add_argument("--no-key", action="store_true", help="Do not issue a new API key")
        parser.add_argument("--republish", action="store_true", help="Overwrite the draft and publish a new version")
        parser.add_argument(
            "--editor-link",
            action="store_true",
            help="Also print a one-time SSO link that opens the editor as project admin (valid 2 minutes)",
        )

    def handle(self, *args: Any, **opts: Any) -> None:
        res = seed(opts["slug"], with_key=not opts["no_key"], republish=opts["republish"])
        p, t = res.project, res.template
        self.stdout.write(f"project:  {p.slug} ({ids.encode('prj', p.id)}) {'created' if res.created else 'exists'}")
        if res.version is not None:
            info = getattr(res.version, "check_render", None)
            self.stdout.write(
                f"template: {t.key} ({ids.encode('tpl', t.id)}) published v{res.version.number}; check render: {info}"
            )
        else:
            self.stdout.write(f"template: {t.key} ({ids.encode('tpl', t.id)}) already published")
        if res.key is not None:
            self.stdout.write(self.style.SUCCESS(f"API key (shown once): {res.key.secret}"))
            self.stdout.write(f"scopes:   {', '.join(res.key.key.scopes)}")
            self.stdout.write(
                "try:      curl -X POST -H 'Authorization: Bearer <key>' -H 'Content-Type: application/json' "
                f"-d '{{\"data\": {{...}}}}' {settings.SNAPFILE_BASE_URL}/api/v1/templates/{t.key}/render"
            )
        if opts["editor_link"]:
            _session, token = issue_session(
                p,
                api_key=None,
                user={"id": "demo-admin", "name": "Demo admin"},
                role="admin",
                open_target={"template": t.key},
            )
            self.stdout.write(self.style.SUCCESS(f"editor:   {settings.SNAPFILE_BASE_URL}/editor/handoff?t={token}"))
            self.stdout.write("          (one-time link, valid for 2 minutes; run the command again for a new one)")
