"""Jupyter Server configuration for DSP docker stack."""
from __future__ import annotations

import os
import re

c = get_config()  # noqa: F821 - provided by Jupyter at runtime

default_app_origins = [
    "http://localhost:8082",
    "http://127.0.0.1:8082",
]
extra_app_origins = [
    value.rstrip("/") for value in os.getenv("DSP_APP_ORIGINS", "").split() if value
]
allowed_app_origins = list(
    dict.fromkeys([origin.rstrip("/") for origin in default_app_origins + extra_app_origins])
)

if allowed_app_origins:
    c.ServerApp.allow_origin = allowed_app_origins[0]
    if len(allowed_app_origins) > 1:
        escaped_origins = [re.escape(origin) for origin in allowed_app_origins]
        pattern = "^(" + "|".join(escaped_origins) + ")$"
        c.ServerApp.allow_origin_pat = pattern

c.ServerApp.allow_remote_access = True
c.ServerApp.disable_check_xsrf = True

default_frame_ancestors = [
    "'self'",
    "http://localhost:8082",
    "http://127.0.0.1:8082",
]
extra_frame_ancestors = [value for value in os.getenv("DSP_FRAME_ANCESTORS", "").split() if value]
frame_ancestors = " ".join(
    dict.fromkeys(default_frame_ancestors + [origin.rstrip("/") for origin in extra_frame_ancestors])
)

c.ServerApp.tornado_settings = {
    "headers": {
        "Content-Security-Policy": f"frame-ancestors {frame_ancestors}",
        "X-Frame-Options": "ALLOWALL",
    }
}
