import flask

from abstra_internals.cloud_api import get_access_controls
from abstra_internals.controllers.main import MainController
from abstra_internals.credentials import resolve_headers
from abstra_internals.environment import IS_PRODUCTION
from abstra_internals.server.guards.role_guard import Guard
from abstra_internals.services.jwt import USER_AUTH_HEADER_KEY
from abstra_internals.usage import editor_usage


def get_editor_bp():
    bp = flask.Blueprint("access_control", __name__)

    # Read-only, and DB-backed: access control is owned by the console now, so the editor reads it
    # from cloud-api (not the local abstra.json). Editing moved to the console — no PUT here. This
    # path serves desktops without the external-player proxy; those with it hit cloud-api's
    # /_web-editor/api/access-control directly.
    @bp.get("/")
    @editor_usage
    def _get_project_level_access_control():
        headers = resolve_headers()
        if not headers:
            return []
        return get_access_controls(headers)

    return bp


def get_player_bp(main_controller: MainController):
    guard = Guard(
        main_controller.users_repository,
        project_repository=main_controller.repositories.project,
        enabled=IS_PRODUCTION,
    )

    bp = flask.Blueprint("player_access_control", __name__)

    @bp.get("/allow/")
    @bp.get("/allow/<path:path>")
    def _get_allow_status_by_path(path: str = ""):
        authHeader = flask.request.headers.get(USER_AUTH_HEADER_KEY)
        return guard.should_allow(path, authHeader).to_dict()

    return bp
