from dotenv import load_dotenv
from pathlib import Path
from datetime import timedelta
import os
from django.templatetags.static import static
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _

# Load environment variables
load_dotenv(".env.local")

# ==============================================================================
# General Configuration
# ==============================================================================
DOMAIN = os.getenv("DOMAIN")
API_DOMAIN = os.getenv("API_DOMAIN")

# API Keys and Tokens
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
TELEGRAM_BOT_TOKEN = '7068288679:AAGecMnyt9A6R78OQu8nQeISMK1LepX718g'
VAPID_PRIVATE_KEY = os.getenv("VAPID_PRIVATE_KEY")

# Email Configuration
EMAIL_BACKEND = os.getenv("EMAIL_BACKEND")
EMAIL_HOST = os.getenv("EMAIL_HOST")
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD")
DEFAULT_FROM_EMAIL = os.getenv("SECRET_KEY")

# Security and Debugging
SECRET_KEY = os.getenv("SECRET_KEY")
DEBUG = True
BASE_DIR = Path(__file__).resolve().parent.parent.parent

# ==============================================================================
# Application Definition
# ==============================================================================
INSTALLED_APPS = [
    # Unfold Theme
    "unfold",
    "unfold.contrib.filters",
    "unfold.contrib.forms",
    "unfold.contrib.inlines",
    "unfold.contrib.import_export",
    "unfold.contrib.guardian",
    "unfold.contrib.simple_history",
    # Django Core
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.humanize",
    "django.contrib.postgres",
    # Third-Party Apps
    "storages",
    "corsheaders",
    "rest_framework",
    "drf_spectacular",
    "django_cleanup.apps.CleanupConfig",
    "django_filters",
    "rest_framework_simplejwt",
    "rest_framework_simplejwt.token_blacklist",
    "rest_framework.authtoken",
    "import_export",
    "django_jalali",
    'django_celery_beat',
    'azbankgateways',
    # Custom Apps
    "product",
    "account",
    "ticket",
    "chat",
    "order",
    "home",
    "blog",
]

# ==============================================================================
# Middleware Configuration
# ==============================================================================
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "core.urls"

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

WSGI_APPLICATION = "core.wsgi.application"

# ==============================================================================
# Authentication and Password Validation
# ==============================================================================
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",
    },
]

LANGUAGE_CODE = "fa"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
ALLOW_UNICODE_SLUGS = True
# ==============================================================================
# Static Files Configuration
# ==============================================================================
STATICFILES_DIRS = [
    # os.path.join(BASE_DIR, "custom_static"),
    BASE_DIR / "core" / "static",
]




STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
AUTH_USER_MODEL = "account.User"

# ==============================================================================
# REST Framework Configuration
# ==============================================================================
REST_FRAMEWORK = {
    # "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
        "rest_framework.renderers.BrowsableAPIRenderer",
    ],
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
    ),
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
    # "DEFAULT_PERMISSION_CLASSES": [
    #     "rest_framework.permissions.IsAuthenticated",
    # ],
}

# ==============================================================================
# Simple JWT Configuration
# ==============================================================================
SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(days=1),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=7),
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,
}

# ==============================================================================
# Spectacular (API Documentation) Configuration
# ==============================================================================
SPECTACULAR_SETTINGS = {
    "TITLE": os.getenv("SITE_TITLE"),
    "DESCRIPTION": os.getenv("SITE_TITLE"),
    "VERSION": "2.0.0",
    "SERVE_INCLUDE_SCHEMA": False,
    "COMPONENT_SPLIT_REQUEST": True,
    "SWAGGER_UI_SETTINGS": {
        "persistAuthorization": True,
    },
}

# ==============================================================================
# Persian Datetime Configuration
# ==============================================================================
JALALI_SETTINGS = {
    "ADMIN_JS_STATIC_FILES": [
        "admin/jquery.ui.datepicker.jalali/scripts/jquery-1.10.2.min.js",
        "admin/jquery.ui.datepicker.jalali/scripts/jquery.ui.core.js",
        "admin/jquery.ui.datepicker.jalali/scripts/jquery.ui.datepicker-cc.js",
        "admin/jquery.ui.datepicker.jalali/scripts/calendar.js",
        "admin/jquery.ui.datepicker.jalali/scripts/jquery.ui.datepicker-cc-fa.js",
        "admin/main.js",
    ],
    "ADMIN_CSS_STATIC_FILES": {
        "all": [
            "admin/jquery.ui.datepicker.jalali/themes/base/jquery-ui.min.css",
            "admin/css/main.css",
        ]
    },
}


# ==============================================================================
# AWS S3 setting for production
# ==============================================================================
AWS_ACCESS_KEY_ID = 'mtiSN2JWjWgyfr2u'
AWS_SECRET_ACCESS_KEY = 'ZGmOM6ekLJEswJS1kOLp49B8DQ3GT0HZ'
AWS_STORAGE_BUCKET_NAME = 'c262408'
AWS_S3_ENDPOINT_URL = 'https://parspack.net'
AWS_S3_REGION_NAME = 'default'  
AWS_S3_SIGNATURE_VERSION = 's3'
AWS_S3_ADDRESSING_STYLE = 'virtual'
AWS_QUERYSTRING_AUTH = False
AWS_DEFAULT_ACL = None
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
    'ACL': 'public-read',
}

# ==============================================================================
#  bank gateway configs 
# ==============================================================================

AZ_IRANIAN_BANK_GATEWAYS = {
    "GATEWAYS": {
        "ZIBAL": {
            "MERCHANT_CODE": "zibal",
            "SANDBOX": True
        }
    },
    "IS_SAMPLE_FORM_ENABLE": True, 
    "DEFAULT": "ZIBAL",
    "CURRENCY": "IRT",  
    "TRACKING_CODE_QUERY_PARAM": "tc",  
    "TRACKING_CODE_LENGTH": 16,  
    "SETTING_VALUE_READER_CLASS": "azbankgateways.readers.DefaultReader",  
    "BANK_PRIORITIES": [
        "ZIBAL",
    ],  
    "IS_SAFE_GET_GATEWAY_PAYMENT": True  # better to be True
}
DEFAULT_TAX_RATE = 0


HANDLER403 = "core.views.custom_permission_denied"
HANDLER404 = 'core.views.handler404'
HANDLER500 = 'core.views.handler500'