"""One-time sign-in link to the editor and dashboard of a project, for installs without an external system."""

from __future__ import annotations

from typing import Any

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

from snapfile.auth_sso.sessions import issue_session
from snapfile.projects.models import Project


class Command(BaseCommand):
    help = "Print a one-time editor sign-in link: snapfile_editor_link <slug> [--role admin] [--name 'Anna']"

    def add_arguments(self, parser: Any) -> None:
        parser.add_argument("slug")
        parser.add_argument("--role", default="admin", choices=["viewer", "editor", "admin"])
        parser.add_argument("--name", default="Administrator", help="Name shown in the editor")
        parser.add_argument("--user-id", default="cli-admin", help="Stable id of the person (locks, history)")

    def handle(self, *args: Any, **opts: Any) -> None:
        project = Project.objects.filter(slug=opts["slug"]).first()
        if project is None:
            raise CommandError(f"project {opts['slug']!r} not found (create it with snapfile_project_create)")
        _session, token = issue_session(
            project, api_key=None, user={"id": opts["user_id"], "name": opts["name"]}, role=opts["role"]
        )
        self.stdout.write(self.style.SUCCESS(f"{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")
