"""Idempotently create the service user that JWT-authenticated MCP requests act as.

Daedalus mints per-turn JWTs whose claims encode all authorization (workspace,
allowed libraries). The Django ``user`` field on the request still needs to
point at *something* — the service user is that something. It owns no data
and does not log in via the dashboard.
"""

import secrets

from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Idempotently create or reactivate the JWT service user (default 'daedalus-service')."

    def add_arguments(self, parser):
        parser.add_argument("--username", default="daedalus-service")
        parser.add_argument("--email", default="daedalus-service@local")
        parser.add_argument(
            "--password",
            default=None,
            help=(
                "Password for HTTP Basic auth (Daedalus REST calls). "
                "Omit to set a random unusable password (JWT-only mode)."
            ),
        )

    def handle(self, *args, **options):
        User = get_user_model()
        username = options["username"]
        email = options["email"]
        password = options["password"] or secrets.token_urlsafe(32)

        user, created = User.objects.get_or_create(
            username=username,
            defaults={"email": email, "is_active": True},
        )
        if created:
            user.set_password(password)
            user.save(update_fields=["password"])
            self.stdout.write(self.style.SUCCESS(f"Created service user {username!r}"))
        else:
            changed = False
            if not user.is_active:
                user.is_active = True
                changed = True
            if user.email != email:
                user.email = email
                changed = True
            if options["password"]:
                user.set_password(password)
                changed = True
            if changed:
                user.save(update_fields=["is_active", "email", "password"])
                self.stdout.write(self.style.SUCCESS(f"Updated service user {username!r}"))
            else:
                self.stdout.write(f"Service user {username!r} already provisioned")
