from django.urls import reverse_lazy
from string import Template
from pathlib import Path
import os
from dotenv import load_dotenv
from datetime import timedelta
from .plugins import get_enabled_apps_list
import sys
# Force reload: 2026-02-06 01:05


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR / ".env")
PLUGINS_DIR = os.path.join(BASE_DIR, "plugins")
sys.path.insert(0, PLUGINS_DIR)
SERVICES_DIR = os.path.join(BASE_DIR, "services")
sys.path.insert(0, SERVICES_DIR)
DEBUG = os.getenv("DEBUG", default=0) == "True"

ASGI_APPLICATION = "lariv.asgi.application"

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-(g0yrp^04x9&4ab=x81o=7^w0n=2h3v^nnylw3i%4v183ufaso"

# SECURITY WARNING: don't run with debug turned on in production!

ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "localhost,127.0.0.1").split(",")

CSRF_TRUSTED_ORIGINS = os.getenv(
    "DJANGO_CSRF_TRUSTED_ORIGINS", "https://127.0.0.1"
).split(",")

CORS_ALLOW_CREDENTIALS = True

# Application definition
# Where we will be adding which apps to enable or disable
ENABLED_APPS = [
    "components",
    "users",
] + get_enabled_apps_list([PLUGINS_DIR, SERVICES_DIR])

INSTALLED_APPS = [
    "daphne",
    "django.contrib.admin",
    "django.contrib.gis",
    "django_extensions",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "storages",
    "corsheaders",
    "pwa",
    "heroicons",
    "django_htmx",
    "treebeard",
    "tailwind",
    "theme",
    "import_export",
    "lariv",
    "huey.contrib.djhuey",
] + ENABLED_APPS

TAILWIND_APP_NAME = "theme"

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.auth.middleware.LoginRequiredMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "django_htmx.middleware.HtmxMiddleware",
]

SESSION_ENGINE = "django.contrib.sessions.backends.cache"

ROOT_URLCONF = "lariv.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [
            BASE_DIR / "lariv" / "templates",
            BASE_DIR / "components",
        ],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
            "builtins": [
                "heroicons.templatetags.heroicons",
            ],
        },
    },
]

WSGI_APPLICATION = "lariv.wsgi.application"


DATABASES = {
    "sqlite": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / f"{os.getenv('DB_NAME')}.sqlite3",
    },
    "postgis": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": os.getenv("DB_NAME"),
        "USER": os.getenv("DB_USER"),
        "PASSWORD": os.getenv("DB_PASSWORD"),
        "HOST": os.getenv("DB_HOST"),
        "PORT": os.getenv("DB_PORT"),
        "OPTIONS": {
            "pool": True,
        },
    },
}

DATABASES["default"] = DATABASES[os.getenv("DB_TYPE", "sqlite")]


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",
    },
]

AUTH_USER_MODEL = "users.User"
LOGIN_REDIRECT_URL = reverse_lazy("apps")
LOGIN_URL = reverse_lazy("users:login")

EMAIL_HOST = os.getenv("EMAIL_HOST")
EMAIL_PORT = os.getenv("EMAIL_PORT")
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", EMAIL_HOST_USER)


# Internationalization
# https://docs.djangoproject.com/en/5.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "Asia/Kolkata"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/

STATIC_URL = "static/"

STATIC_ROOT = os.getenv("STATIC_ROOT")

STATICFILES_DIRS = [BASE_DIR / "static"]
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

PHONENUMBER_DEFAULT_REGION = "IN"
GS_BUCKET_NAME = "lariv-bucket"

if not DEBUG:
    STORAGES = {
        "default": {
            "BACKEND": "storages.backends.gcloud.GoogleCloudStorage",
            "OPTIONS": {
                "bucket_name": GS_BUCKET_NAME,
                "file_overwrite": False,
                "iam_sign_blob": True,
                "querystring_auth": False,
            },
        },
        "staticfiles": {
            "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
        },
    }

    MEDIA_URL = "https://storage.googleapis.com/{}/".format(GS_BUCKET_NAME)

    GCS_ROOT = "https://storage.googleapis.com/{bucket_name}/".format(
        bucket_name=GS_BUCKET_NAME
    )

    MEDIA_PREFIX = "media"
    MEDIA_URL = "{gcs_root}{prefix}/".format(
        gcs_root=GCS_ROOT,
        prefix=MEDIA_PREFIX,
    )

# PWA Settings
PWA_APP_NAME = os.getenv("PWA_APP_NAME", "Lariv")
PWA_APP_DESCRIPTION = os.getenv("PWA_APP_DESCRIPTION", "Lariv Application")
PWA_APP_THEME_COLOR = "#000000"
PWA_APP_BACKGROUND_COLOR = "#ffffff"
PWA_APP_DISPLAY = "standalone"
PWA_APP_SCOPE = "/"
PWA_APP_ORIENTATION = "any"
PWA_APP_START_URL = "/"
PWA_APP_STATUS_BAR_COLOR = "default"
PWA_ICON_PATHS = os.getenv(
    "PWA_ICON_PATH",
    [
        {
            "src": "/static/icons/Lariv Logo 192x192.png",
            "sizes": "192x192",
        },
        {
            "src": "/static/icons/Lariv Logo 512x512.png",
            "sizes": "512x512",
        },
    ],
)
PWA_ICON_PATHS_APPLE = os.getenv(
    "PWA_ICON_PATH",
    [
        {
            "src": "/static/icons/Lariv Logo 192x192.png",
            "sizes": "192x192",
        },
    ],
)
if not DEBUG:
    PWA_APP_ICONS = (
        (exec(PWA_ICON_PATHS) if isinstance(PWA_ICON_PATHS, str) else PWA_ICON_PATHS),
    )
    PWA_APP_ICONS_APPLE = (
        exec(PWA_ICON_PATHS_APPLE)
        if isinstance(PWA_ICON_PATHS_APPLE, str)
        else PWA_ICON_PATHS_APPLE
    )
else:
    PWA_APP_ICONS = [
        {
            "src": "/static/icons/debug/Lariv Logo 192x192.png",
            "sizes": "192x192",
        },
        {
            "src": "/static/icons/debug/Lariv Logo 512x512.png",
            "sizes": "512x512",
        },
    ]
    PWA_APP_ICONS_APPLE = [
        {
            "src": "/static/icons/debug/Lariv Logo 192x192.png",
            "sizes": "192x192",
        },
    ]

PWA_APP_SPLASH_SCREEN = []
PWA_APP_DIR = "ltr"
PWA_APP_LANG = "en-US"

if DEBUG:
    # Add django_browser_reload only in DEBUG mode
    INSTALLED_APPS += [
        "django_browser_reload",
        "django_watchfiles",
    ]
    MIDDLEWARE += [
        "django_browser_reload.middleware.BrowserReloadMiddleware",
    ]

    MEDIA_URL = "/media/"
    MEDIA_ROOT = "media/"


HUEY = {
    "consumer": {
        "worker_type": "greenlet",
    },
}
