"""Durable non-login attribution for trusted automated domain workflows.

Do not use this principal for authorization. It can only be attributed as an
actor in immutable evidence produced by code already authorized to run.
"""
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ImproperlyConfigured


SYSTEM_ACTOR_EMAIL = "ftg2-automation@internal.invalid"
SYSTEM_ACTOR_USERNAME = "ftg2-system-automation"


def get_system_actor():
    """Return an inactive, unprivileged, non-login audit principal.

    The unique email makes first creation idempotent (including concurrent
    workers on PostgreSQL). Existing principals are checked to avoid silently
    repurposing a human account if deployment data contains a collision.
    """
    User = get_user_model()
    user, created = User.objects.get_or_create(
        email=SYSTEM_ACTOR_EMAIL,
        defaults={
            "username": SYSTEM_ACTOR_USERNAME,
            "password": make_password(None),
            "display_name": "FTG2 automated domain operation",
            "is_active": False,
            "is_staff": False,
            "is_superuser": False,
            "is_email_verified": False,
        },
    )
    if (
        user.username != SYSTEM_ACTOR_USERNAME
        or user.is_active
        or user.is_staff
        or user.is_superuser
        or user.has_usable_password()
    ):
        raise ImproperlyConfigured("The reserved FTG2 system audit principal is not a disabled service account.")
    return user


def is_system_actor(user):
    """Recognition is deliberately separate from auth and never grants login."""
    return bool(
        user is not None
        and getattr(user, "pk", None)
        and getattr(user, "email", None) == SYSTEM_ACTOR_EMAIL
        and getattr(user, "username", None) == SYSTEM_ACTOR_USERNAME
        and getattr(user, "is_active", True) is False
        and getattr(user, "is_staff", True) is False
        and getattr(user, "is_superuser", True) is False
        and not user.has_usable_password()
    )
