"""Narrow internal delegation for a mother-approved automatic season workflow.

This does not grant portal, treasury, discipline or appointment permissions.
The context exists only while the automatic competition workflow is executing.
"""

from contextlib import contextmanager
from contextvars import ContextVar

_execution = ContextVar("season_execution_authority", default=None)


@contextmanager
def season_execution_authority(policy):
    from federations.access import can_control_federation
    from federations.models import Federation

    from .exceptions import SeasonActivationGateError

    mother = Federation.objects.filter(
        federation_type="MOTHER", status="ACTIVE"
    ).first()
    if mother is None or not can_control_federation(policy.operator, mother):
        raise SeasonActivationGateError(
            "Automatic competition workflow requires current mother federation governance authority."
        )
    token = _execution.set((policy.operator_id, mother.pk))
    try:
        yield
    finally:
        _execution.reset(token)


def permits_competition_execution(user, federation, roles):
    context = _execution.get()
    return bool(
        context
        and user
        and context[0] == user.pk
        and set(roles) <= {"GOVERNOR", "COMPETITION"}
        and federation.status == "ACTIVE"
        and (federation.pk == context[1] or federation.parent_id == context[1])
    )
