import os
import sys
from pathlib import Path

from django.templatetags.static import static
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _

BASE_DIR = Path(__file__).resolve().parent.parent


def env(name, default=None):
    value = os.getenv(name, default)
    if isinstance(default, bool):
        return str(value).lower() in {"1", "true", "yes", "on"}
    return value


# Carregamento simples do ficheiro .env, sem dependência adicional.
env_file = BASE_DIR / ".env"
if env_file.exists():
    for raw_line in env_file.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ.setdefault(key.strip(), value.strip())

SECRET_KEY = env("SECRET_KEY", "django-insecure-development-only")
DEBUG = env("DEBUG", True)
DEMO_MODE = env("DEMO_MODE", False)
K4W_VERSION = env("K4W_VERSION", "9.4.0")
K4W_ENVIRONMENT = env("K4W_ENVIRONMENT", "Desenvolvimento" if DEBUG else "Produção")
DEMO_CREDENTIALS_VISIBLE = env("DEMO_CREDENTIALS_VISIBLE", DEBUG or DEMO_MODE)
K4W_REQUIRE_2FA_FOR_STAFF = env("K4W_REQUIRE_2FA_FOR_STAFF", False)
K4W_DATABASE_MAINTENANCE_ENABLED = env("K4W_DATABASE_MAINTENANCE_ENABLED", DEBUG or DEMO_MODE)
K4W_DATABASE_MAINTENANCE_ALLOW_FULL_RESET = env("K4W_DATABASE_MAINTENANCE_ALLOW_FULL_RESET", DEBUG or DEMO_MODE)
K4W_MONITOR_ALLOW_PRIVATE_NETWORKS = env("K4W_MONITOR_ALLOW_PRIVATE_NETWORKS", DEBUG)
K4W_MONITOR_HISTORY_DAYS = int(env("K4W_MONITOR_HISTORY_DAYS", "180"))
K4W_MONITOR_MAX_BODY_BYTES = int(env("K4W_MONITOR_MAX_BODY_BYTES", "1048576"))
K4W_MONITOR_USER_AGENT = env("K4W_MONITOR_USER_AGENT", "Kreate4Web-Monitor/9.4")
OTP_TOTP_ISSUER = env("OTP_TOTP_ISSUER", "Kreate4Web")
ALLOWED_HOSTS = [x.strip() for x in env("ALLOWED_HOSTS", "127.0.0.1,localhost").split(",") if x.strip()]
CSRF_TRUSTED_ORIGINS = [x.strip() for x in env("CSRF_TRUSTED_ORIGINS", "").split(",") if x.strip()]

INSTALLED_APPS = [
    "devtools.apps.DevtoolsConfig",
    "unfold",
    "unfold.contrib.filters",
    "unfold.contrib.simple_history",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "simple_history",
    "django_celery_beat",
    "django_otp",
    "django_otp.plugins.otp_totp",
    "security.apps.SecurityConfig",
    "maintenance.apps.MaintenanceConfig",
    "core",
    "clients",
    "services",
    "domains",
    "technical",
    "monitoring.apps.MonitoringConfig",
    "hosting",
    "websites",
    "billing",
    "notifications",
    "template_library.apps.TemplateLibraryConfig",
    "operations.apps.OperationsConfig",
    "support.apps.SupportConfig",
    "imports.apps.ImportsConfig",
    "dashboard",
    "client_portal.apps.ClientPortalConfig",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django_otp.middleware.OTPMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "security.middleware.UnifiedLoginAndTwoFactorMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "simple_history.middleware.HistoryRequestMiddleware",
]

ROOT_URLCONF = "config.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                "security.context_processors.k4w_shell",
            ],
        },
    },
]

WSGI_APPLICATION = "config.wsgi.application"

if env("DB_ENGINE", "sqlite") == "postgres":
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.postgresql",
            "NAME": env("DB_NAME"),
            "USER": env("DB_USER"),
            "PASSWORD": env("DB_PASSWORD"),
            "HOST": env("DB_HOST", "localhost"),
            "PORT": env("DB_PORT", "5432"),
            "CONN_MAX_AGE": 60,
        }
    }
else:
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": BASE_DIR / "db.sqlite3",
        }
    }

AUTH_PASSWORD_VALIDATORS = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
PASSWORD_RESET_TIMEOUT = int(env("PASSWORD_RESET_TIMEOUT", "3600"))
if "test" in sys.argv:
    PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]



LANGUAGE_CODE = "pt-pt"
TIME_ZONE = "Europe/Lisbon"
USE_I18N = True
USE_TZ = True

STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [BASE_DIR / "static"]
STORAGES = {
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {
        "BACKEND": (
            "django.contrib.staticfiles.storage.StaticFilesStorage"
            if DEBUG
            else "whitenoise.storage.CompressedManifestStaticFilesStorage"
        )
    },
}
MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "media"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

AUTHENTICATION_BACKENDS = [
    "core.auth_backends.UsernameOrEmailBackend",
]

# Em desenvolvimento local, localhost deve permanecer em HTTP. O comando
# runserver reforça estas opções para evitar redirecionamentos para HTTPS.
LOCAL_DEVELOPMENT = env("LOCAL_DEVELOPMENT", DEBUG)
if LOCAL_DEVELOPMENT:
    SECURE_SSL_REDIRECT = False
    SESSION_COOKIE_SECURE = False
    CSRF_COOKIE_SECURE = False
    for local_host in ("127.0.0.1", "localhost", "[::1]"):
        if local_host not in ALLOWED_HOSTS:
            ALLOWED_HOSTS.append(local_host)

EMAIL_BACKEND = env("EMAIL_BACKEND", "django.core.mail.backends.console.EmailBackend")
DEFAULT_FROM_EMAIL = env("DEFAULT_FROM_EMAIL", "Kreate4Web <noreply@kreate4web.com>")
EMAIL_HOST = env("EMAIL_HOST", "")
EMAIL_PORT = int(env("EMAIL_PORT", "587"))
EMAIL_HOST_USER = env("EMAIL_HOST_USER", "")
EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD", "")
EMAIL_USE_TLS = env("EMAIL_USE_TLS", True)
EMAIL_USE_SSL = env("EMAIL_USE_SSL", False)
EMAIL_TIMEOUT = int(env("EMAIL_TIMEOUT", "20"))

CELERY_BROKER_URL = env("CELERY_BROKER_URL", "redis://127.0.0.1:6379/0")
CELERY_RESULT_BACKEND = env("CELERY_RESULT_BACKEND", "redis://127.0.0.1:6379/1")
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
CELERY_TIMEZONE = TIME_ZONE
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = int(env("CELERY_TASK_TIME_LIMIT", "300"))
CELERY_TASK_SOFT_TIME_LIMIT = int(env("CELERY_TASK_SOFT_TIME_LIMIT", "240"))
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
CELERY_TASK_ALWAYS_EAGER = env("CELERY_TASK_ALWAYS_EAGER", False)
CELERY_TASK_EAGER_PROPAGATES = True

SECURE_SSL_REDIRECT = False if LOCAL_DEVELOPMENT else env("SECURE_SSL_REDIRECT", False)
SESSION_COOKIE_SECURE = False if LOCAL_DEVELOPMENT else env("SESSION_COOKIE_SECURE", False)
CSRF_COOKIE_SECURE = False if LOCAL_DEVELOPMENT else env("CSRF_COOKIE_SECURE", False)
SECURE_HSTS_SECONDS = int(env("SECURE_HSTS_SECONDS", "0"))
SECURE_HSTS_INCLUDE_SUBDOMAINS = env("SECURE_HSTS_INCLUDE_SUBDOMAINS", False)
SECURE_HSTS_PRELOAD = env("SECURE_HSTS_PRELOAD", False)
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_REFERRER_POLICY = "same-origin"
X_FRAME_OPTIONS = "DENY"
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
CSRF_COOKIE_HTTPONLY = True
CSRF_COOKIE_SAMESITE = "Lax"
FILE_UPLOAD_PERMISSIONS = 0o640

UNFOLD = {
    "SITE_TITLE": "Portal Kreate4Web",
    "SITE_HEADER": "Kreate4Web",
    "SITE_SUBHEADER": "Gestão de serviços digitais",
    "SITE_SYMBOL": "hub",
    "SITE_ICON": {
        "light": lambda request: static("branding/kreate4web-mark.png"),
        "dark": lambda request: static("branding/kreate4web-mark.png"),
    },
    "SITE_LOGO": {
        "light": lambda request: static("branding/kreate4web-logo-horizontal.png"),
        "dark": lambda request: static("branding/kreate4web-logo-horizontal.png"),
    },
    "SITE_FAVICONS": [
        {
            "rel": "icon",
            "sizes": "32x32",
            "type": "image/png",
            "href": lambda request: static("branding/kreate4web-favicon.png"),
        },
    ],
    "SITE_URL": "/admin/",
    "SHOW_HISTORY": True,
    "SHOW_VIEW_ON_SITE": False,
    "SHOW_BACK_BUTTON": True,
    "DASHBOARD_CALLBACK": "dashboard.views.dashboard_callback",
    "ENVIRONMENT": "dashboard.views.environment_callback",
    "LOGIN": {
        "image": lambda request: static("branding/login-visual-k4w.svg"),
        "redirect_after": lambda request: reverse_lazy("admin:index"),
    },
    "STYLES": [lambda request: static("css/admin.css")],
    "SCRIPTS": [lambda request: static("js/admin-dashboard.js")],
    "BORDER_RADIUS": "14px",
    "COLORS": {
        "base": {
            "50": "oklch(98.4% .006 247)",
            "100": "oklch(96.7% .010 250)",
            "200": "oklch(92.4% .018 252)",
            "300": "oklch(85.9% .030 252)",
            "400": "oklch(68.4% .044 254)",
            "500": "oklch(53.8% .050 257)",
            "600": "oklch(43.8% .049 258)",
            "700": "oklch(35.9% .046 258)",
            "800": "oklch(26.5% .039 260)",
            "900": "oklch(19.8% .034 262)",
            "950": "oklch(12.8% .028 263)",
        },
        "primary": {
            "50": "oklch(98.7% .035 98)",
            "100": "oklch(96.8% .090 96)",
            "200": "oklch(92.5% .150 94)",
            "300": "oklch(87.5% .185 91)",
            "400": "oklch(82.5% .190 87)",
            "500": "oklch(78.2% .185 83)",
            "600": "oklch(67.5% .165 77)",
            "700": "oklch(56.0% .142 70)",
            "800": "oklch(47.0% .118 65)",
            "900": "oklch(41.0% .095 61)",
            "950": "oklch(28.0% .065 56)",
        },
        "font": {
            "subtle-light": "var(--color-base-500)",
            "subtle-dark": "var(--color-base-400)",
            "default-light": "var(--color-base-700)",
            "default-dark": "var(--color-base-300)",
            "important-light": "var(--color-base-950)",
            "important-dark": "var(--color-base-50)",
        },
    },
    "COMMAND": {
        "search_models": [
            "clients.client",
            "services.service",
            "domains.domain",
            "hosting.hostingaccount",
            "websites.websiteproject",
            "operations.internaltask",
            "imports.importbatch",
            "imports.importrow",
            "imports.importedobject",
            "clients.clientportalaccess",
            "support.supportticket",
            "support.supportmessage",
            "template_library.reusabletemplate",
            "template_library.formtemplate",
            "template_library.templatecategory",
            "technical.wordpresssite",
            "technical.wordpressplugin",
            "technical.wordpresstheme",
            "technical.sslcertificate",
        ],
        "show_history": True,
    },
    "SIDEBAR": {
        "show_search": True,
        "command_search": True,
        "show_all_applications": False,
        "navigation": [
            {
                "title": _("Visão geral"),
                "separator": False,
                "items": [
                    {"title": _("Dashboard"), "icon": "dashboard", "link": reverse_lazy("admin:index")},
                    {"title": _("Centro de operações"), "icon": "space_dashboard", "link": reverse_lazy("operations_center")},
                    {"title": _("Tarefas internas"), "icon": "task_alt", "link": reverse_lazy("admin:operations_internaltask_changelist"), "badge": "dashboard.views.task_badge", "badge_variant": "warning"},
                ],
            },
            {
                "title": _("Gestão comercial"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Clientes"), "icon": "groups", "link": reverse_lazy("admin:clients_client_changelist")},
                    {"title": _("Serviços"), "icon": "inventory_2", "link": reverse_lazy("admin:services_service_changelist")},
                    {"title": _("Projetos web"), "icon": "web", "link": reverse_lazy("admin:websites_websiteproject_changelist")},
                    {"title": _("Fornecedores"), "icon": "business", "link": reverse_lazy("admin:core_provider_changelist")},
                ],
            },
            {
                "title": _("Serviços recorrentes"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Domínios"), "icon": "language", "link": reverse_lazy("admin:domains_domain_changelist")},
                    {"title": _("Alojamentos"), "icon": "dns", "link": reverse_lazy("admin:hosting_hostingaccount_changelist")},
                    {"title": _("Renovações"), "icon": "event_repeat", "link": reverse_lazy("admin:billing_renewal_changelist"), "badge": "dashboard.views.renewal_badge", "badge_variant": "primary"},
                ],
            },
            {
                "title": _("Financeiro e comunicações"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Pagamentos"), "icon": "payments", "link": reverse_lazy("admin:billing_payment_changelist"), "badge": "dashboard.views.payment_badge", "badge_variant": "danger"},
                    {"title": _("Centro de comunicações"), "icon": "campaign", "link": reverse_lazy("communications_center")},
                    {"title": _("Notificações"), "icon": "notifications", "link": reverse_lazy("admin:notifications_notificationlog_changelist"), "badge": "dashboard.views.notification_badge", "badge_variant": "info"},
                    {"title": _("Modelos de mensagem"), "icon": "mail", "link": reverse_lazy("admin:notifications_notificationtemplate_changelist")},
                ],
            },
            {
                "title": _("Biblioteca e conteúdos"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Centro de templates"), "icon": "dashboard_customize", "link": reverse_lazy("template_center")},
                    {"title": _("Templates de email"), "icon": "mail", "link": reverse_lazy("admin:notifications_notificationtemplate_changelist")},
                    {"title": _("Conteúdos reutilizáveis"), "icon": "content_copy", "link": reverse_lazy("admin:template_library_reusabletemplate_changelist")},
                    {"title": _("Formulários"), "icon": "dynamic_form", "link": reverse_lazy("admin:template_library_formtemplate_changelist")},
                    {"title": _("Categorias"), "icon": "folder_copy", "link": reverse_lazy("admin:template_library_templatecategory_changelist")},
                    {"title": _("Histórico de utilização"), "icon": "history", "link": reverse_lazy("admin:template_library_templateusage_changelist")},
                ],
            },
            {
                "title": _("Relação com clientes"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Abrir portal do cliente"), "icon": "open_in_new", "link": reverse_lazy("client_portal:dashboard")},
                    {"title": _("Acessos ao portal"), "icon": "account_circle", "link": reverse_lazy("admin:clients_clientportalaccess_changelist")},
                    {"title": _("Pré-visualizar como cliente"), "icon": "preview", "link": reverse_lazy("client_preview_center"), "permission": "dashboard.views.client_preview_permission"},
                    {"title": _("Credenciais de demonstração"), "icon": "password", "link": reverse_lazy("demo_credentials_center"), "permission": "dashboard.views.superuser_demo_permission"},
                    {"title": _("Pedidos de suporte"), "icon": "support_agent", "link": reverse_lazy("admin:support_supportticket_changelist"), "badge": "dashboard.views.support_badge", "badge_variant": "danger"},
                    {"title": _("Mensagens de suporte"), "icon": "forum", "link": reverse_lazy("admin:support_supportmessage_changelist")},
                    {"title": _("Documentos"), "icon": "folder_open", "link": reverse_lazy("admin:core_document_changelist")},
                ],
            },
            {
                "title": _("Infraestrutura"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Centro de monitorização"), "icon": "space_dashboard", "link": reverse_lazy("monitoring_center"), "badge": "dashboard.views.monitoring_badge", "badge_variant": "danger"},
                    {"title": _("Monitores de websites"), "icon": "monitor_heart", "link": reverse_lazy("admin:monitoring_websitemonitor_changelist")},
                    {"title": _("Verificações"), "icon": "fact_check", "link": reverse_lazy("admin:monitoring_monitorcheck_changelist")},
                    {"title": _("Incidentes"), "icon": "crisis_alert", "link": reverse_lazy("admin:monitoring_monitorincident_changelist"), "badge": "dashboard.views.monitoring_badge", "badge_variant": "danger"},
                    {"title": _("Servidores"), "icon": "storage", "link": reverse_lazy("admin:technical_server_changelist")},
                    {"title": _("Ativos técnicos"), "icon": "developer_board", "link": reverse_lazy("admin:technical_technicalasset_changelist")},
                    {"title": _("Bases de dados"), "icon": "database", "link": reverse_lazy("admin:technical_databaseasset_changelist")},
                    {"title": _("Backups"), "icon": "backup", "link": reverse_lazy("admin:technical_backuprecord_changelist")},
                    {"title": _("Dados demo WordPress"), "icon": "science", "link": reverse_lazy("wordpress_demo_center"), "permission": "technical.views.wordpress_demo_permission"},
                    {"title": _("Sites WordPress"), "icon": "web", "link": reverse_lazy("admin:technical_wordpresssite_changelist")},
                    {"title": _("Plugins WordPress"), "icon": "extension", "link": reverse_lazy("admin:technical_wordpressplugin_changelist")},
                    {"title": _("Temas WordPress"), "icon": "palette", "link": reverse_lazy("admin:technical_wordpresstheme_changelist")},
                    {"title": _("Certificados SSL"), "icon": "lock", "link": reverse_lazy("admin:technical_sslcertificate_changelist")},
                ],
            },
            {
                "title": _("Dados e qualidade"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Centro de qualidade"), "icon": "data_check", "link": reverse_lazy("quality_center")},
                    {"title": _("Importações Excel"), "icon": "upload_file", "link": reverse_lazy("admin:imports_importbatch_changelist"), "badge": "dashboard.views.import_badge", "badge_variant": "warning"},
                    {"title": _("Linhas de importação"), "icon": "fact_check", "link": reverse_lazy("admin:imports_importrow_changelist")},
                    {"title": _("Registos importados"), "icon": "inventory", "link": reverse_lazy("admin:imports_importedobject_changelist")},
                    {"title": _("Relatórios"), "icon": "analytics", "link": reverse_lazy("report_center")},
                ],
            },
            {
                "title": _("Sistema"),
                "separator": True,
                "collapsible": True,
                "items": [
                    {"title": _("Configuração"), "icon": "settings", "link": reverse_lazy("admin:core_portalconfiguration_changelist")},
                    {"title": _("A minha conta"), "icon": "manage_accounts", "link": reverse_lazy("security:account")},
                    {"title": _("Segurança e 2FA"), "icon": "security", "link": reverse_lazy("security:overview")},
                    {"title": _("Eventos de segurança"), "icon": "policy", "link": reverse_lazy("admin:security_securityevent_changelist")},
                    {"title": _("Estado e diagnóstico"), "icon": "monitor_heart", "link": reverse_lazy("health")},
                    {"title": _("Manutenção da base de dados"), "icon": "database", "link": reverse_lazy("database_maintenance_center"), "permission": "maintenance.views.database_maintenance_permission"},
                    {"title": _("Histórico de limpezas"), "icon": "history", "link": reverse_lazy("admin:maintenance_databasecleanupoperation_changelist"), "permission": "maintenance.views.database_maintenance_permission"},
                    {"title": _("Legenda de estados"), "icon": "palette", "link": reverse_lazy("status_legend")},
                    {"title": _("Automação periódica"), "icon": "schedule", "link": reverse_lazy("admin:django_celery_beat_periodictask_changelist")},
                    {"title": _("Utilizadores"), "icon": "manage_accounts", "link": reverse_lazy("admin:auth_user_changelist")},
                    {"title": _("Grupos e permissões"), "icon": "admin_panel_settings", "link": reverse_lazy("admin:auth_group_changelist")},
                ],
            },
        ],
    },
    "TABS": [
        {
            "models": ["clients.client", "services.service", "websites.websiteproject"],
            "items": [
                {"title": _("Clientes"), "link": reverse_lazy("admin:clients_client_changelist")},
                {"title": _("Serviços"), "link": reverse_lazy("admin:services_service_changelist")},
                {"title": _("Projetos web"), "link": reverse_lazy("admin:websites_websiteproject_changelist")},
            ],
        },
        {
            "models": ["domains.domain", "hosting.hostingaccount", "billing.renewal"],
            "items": [
                {"title": _("Domínios"), "link": reverse_lazy("admin:domains_domain_changelist")},
                {"title": _("Alojamentos"), "link": reverse_lazy("admin:hosting_hostingaccount_changelist")},
                {"title": _("Renovações"), "link": reverse_lazy("admin:billing_renewal_changelist")},
            ],
        },
        {
            "models": ["billing.payment", "notifications.notificationlog", "core.document"],
            "items": [
                {"title": _("Pagamentos"), "link": reverse_lazy("admin:billing_payment_changelist")},
                {"title": _("Comunicações"), "link": reverse_lazy("admin:notifications_notificationlog_changelist")},
                {"title": _("Documentos"), "link": reverse_lazy("admin:core_document_changelist")},
            ],
        },
        {
            "models": ["operations.internaltask", "support.supportticket", "support.supportmessage", "clients.clientportalaccess"],
            "items": [
                {"title": _("Tarefas"), "link": reverse_lazy("admin:operations_internaltask_changelist")},
                {"title": _("Suporte"), "link": reverse_lazy("admin:support_supportticket_changelist")},
                {"title": _("Mensagens"), "link": reverse_lazy("admin:support_supportmessage_changelist")},
                {"title": _("Acessos ao portal"), "link": reverse_lazy("admin:clients_clientportalaccess_changelist")},
            ],
        },
        {
            "models": ["notifications.notificationtemplate", "template_library.reusabletemplate", "template_library.formtemplate", "template_library.templatecategory"],
            "items": [
                {"title": _("Centro de templates"), "link": reverse_lazy("template_center")},
                {"title": _("Emails"), "link": reverse_lazy("admin:notifications_notificationtemplate_changelist")},
                {"title": _("Conteúdos"), "link": reverse_lazy("admin:template_library_reusabletemplate_changelist")},
                {"title": _("Formulários"), "link": reverse_lazy("admin:template_library_formtemplate_changelist")},
            ],
        },
        {
            "models": ["technical.server", "technical.technicalasset", "technical.wordpresssite", "technical.wordpressplugin", "technical.wordpresstheme", "technical.sslcertificate", "monitoring.websitemonitor", "monitoring.monitorcheck", "monitoring.monitorincident"],
            "items": [
                {"title": _("Monitorização"), "link": reverse_lazy("monitoring_center")},
                {"title": _("Monitores"), "link": reverse_lazy("admin:monitoring_websitemonitor_changelist")},
                {"title": _("Incidentes"), "link": reverse_lazy("admin:monitoring_monitorincident_changelist")},
                {"title": _("Servidores"), "link": reverse_lazy("admin:technical_server_changelist")},
                {"title": _("Ativos"), "link": reverse_lazy("admin:technical_technicalasset_changelist")},
                {"title": _("WordPress"), "link": reverse_lazy("admin:technical_wordpresssite_changelist")},
                {"title": _("Plugins"), "link": reverse_lazy("admin:technical_wordpressplugin_changelist")},
                {"title": _("Temas"), "link": reverse_lazy("admin:technical_wordpresstheme_changelist")},
                {"title": _("SSL"), "link": reverse_lazy("admin:technical_sslcertificate_changelist")},
            ],
        },
        {
            "models": ["imports.importbatch", "imports.importrow"],
            "items": [
                {"title": _("Ficheiros Excel"), "link": reverse_lazy("admin:imports_importbatch_changelist")},
                {"title": _("Revisão de dados"), "link": reverse_lazy("admin:imports_importrow_changelist")},
            ],
        },
    ],
}

LOGIN_URL = "security:login"
LOGIN_REDIRECT_URL = "home"
LOGOUT_REDIRECT_URL = "security:login"
FILE_UPLOAD_MAX_MEMORY_SIZE = 8 * 1024 * 1024
DATA_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024
