import os
from pathlib import Path
from datetime import timedelta

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-your-secret-key-here'

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

ALLOWED_HOSTS = []

# Email settings for development
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Email settings for production
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'delta.xkhl@gmail.com'  # Remplace par ton email
EMAIL_HOST_PASSWORD = 'txhg setj xutv vjxv'  # Remplace par ton mot de passe
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Third party apps
    'rest_framework',
    'rest_framework.authtoken',  # Add this line
    'corsheaders',
    'rest_framework_simplejwt',
    # Social Authentication
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'dj_rest_auth',
    'dj_rest_auth.registration',
    # Project apps
    'main',
    'users',
    'slider',
    'about_us',
    'events',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # Make sure this is before other middleware
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'allauth.account.middleware.AccountMiddleware',  # Add this line
]

ROOT_URLCONF = 'delta_project.urls'

# main settings
# Make sure these settings are correct
CORS_ALLOWED_ORIGINS = [
    "https://www.deltax.atcdz.com",
    "https://www.deltax.atcdz.com",
    # Add any other origins you're using
]

CORS_ALLOW_CREDENTIALS = True



# Allow CSRF token in requests
CSRF_COOKIE_HTTPONLY = False  # Allow frontend JS to access it
CSRF_COOKIE_SAMESITE = "Lax"  # Adjust if needed
# Also update ALLOWED_HOSTS to include your IP
ALLOWED_HOSTS = ['localhost', '127.0.0.1', '*']

# For django-allauth, add this setting
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'http'

# Make sure CSRF settings allow your frontend
CSRF_TRUSTED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
    "https://www.deltax.atcdz.com",
]


# CSRF settings
CSRF_COOKIE_SECURE = False  # Set to True in production with HTTPS
CSRF_COOKIE_HTTPONLY = False  # Allow JavaScript to access the cookie
CSRF_COOKIE_SAMESITE = 'Lax'  # Recommended setting for most cases
CSRF_USE_SESSIONS = False  # Store CSRF token in cookie, not session
CSRF_COOKIE_NAME = 'csrftoken'  # Default name, but explicitly set it

# Add CSRF exempt for Google auth endpoint
CSRF_EXEMPT_URLS = ['/api/auth/google/']

CSRF_COOKIE_SECURE = False  # Set to True only in production (HTTPS)
CSRF_COOKIE_HTTPONLY = False  # Allow JS to access CSRF token if needed
CSRF_USE_SESSIONS = False  # Use cookie-based CSRF protection
SESSION_COOKIE_SECURE = False  # Disable secure session cookies in dev

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'delta_project.wsgi.application'

# Database
DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
    'default': {
        'ENGINE': os.environ.get('DB_ENGINE', "django.db.backends.mysql"),
        'NAME': os.environ.get('DB_NAME', 'atcdwxoj_deltax'),
        'USER': os.environ.get('DB_USER', 'atcdwxoj_deltax'),
        'PASSWORD': os.environ.get('DB_PASSWORD', 'Deltax@ecole2029'),
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '3306'),
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            # Add this to disable features not supported in older MariaDB
            
        },
        'features': {
                'supports_transactions': False,
                'supports_column_check_constraints': False,
                'supports_table_check_constraints': False,
                'supports_json_field': False,
            },
            
    }
    
    # 'default': {
    #     'ENGINE': 'django.db.backends.postgresql',
    #     'NAME': os.environ.get('DB_NAME', 'atcdwxoj_deltax_db'),
    #     'USER': os.environ.get('DB_USER', 'atcdwxoj_deltax'),
    #     'PASSWORD': os.environ.get('DB_PASSWORD', 'Deltax@ecole2029'),
    #     'HOST': os.environ.get('DB_HOST', '127.0.0.200'),
    #     'PORT': os.environ.get('DB_PORT', '5432'),
    # }
}


# Custom user model
AUTH_USER_MODEL = 'users.User'

# 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',
    },
]

# REST Framework settings
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'dj_rest_auth.jwt_auth.JWTCookieAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ],
}

# JWT settings
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}

# Site ID for django-allauth
SITE_ID = 1

# Authentication backends
AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend',
]

# Google OAuth2 settings
SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'APP': {
            'client_id': '699511235834-l0kgb3i219n49felfjn1mn0k0bf0ju6p.apps.googleusercontent.com',
            'secret': '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',
            'key': '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'
        },
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        },
        'VERIFIED_EMAIL': True,  # Add this line to trust Google's email verification
        'OAUTH_PKCE_ENABLED': True,  # Add this for better security
    }
}

# Add these settings for Google login
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"  # Since Google already verifies emails
SOCIALACCOUNT_AUTO_SIGNUP = True  # Allow auto signup with social accounts
SOCIALACCOUNT_ADAPTER = "users.adapters.CustomSocialAccountAdapter"  # You'll need to create this


ACCOUNT_ADAPTER = "allauth.account.adapter.DefaultAccountAdapter"
SOCIALACCOUNT_ADAPTER = "allauth.socialaccount.adapter.DefaultSocialAccountAdapter"

# Rest auth settings
# Add these settings to customize the password reset URL
# This will make the reset link point to your frontend application
# Set the frontend URL for password reset
FRONTEND_URL = 'http://deltax.atcdz.com'

# Django Sites Framework configuration
SITE_ID = 1

# Django AllAuth settings
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"  # Use "https" in production
ACCOUNT_EMAIL_VERIFICATION = "optional"

ACCOUNT_UNIQUE_EMAIL = True



# dj-rest-auth settings
# Add or update these settings
REST_AUTH = {
    'USER_DETAILS_SERIALIZER': 'users.serializers.UserSerializer',
    'TOKEN_MODEL': None,  # We're using JWT tokens
    'SESSION_LOGIN': False,
    'USE_JWT': True,
    'JWT_AUTH_COOKIE': 'auth',
    'JWT_AUTH_REFRESH_COOKIE': 'refresh-token',
}

# Django-allauth settings
# ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
# ACCOUNT_USERNAME_REQUIRED = True
# ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_SUBJECT_PREFIX = "DeltaX - "

# Set the adapter
ACCOUNT_ADAPTER = 'users.adapters.CustomAccountAdapter'

# Make sure your frontend domain is included in allowed hosts
#ALLOWED_HOSTS = ['localhost', '127.0.0.1', '*']



# Update dj-rest-auth settings
# Add these settings for django-allauth to fix the deprecation warning

ACCOUNT_UNIQUE_EMAIL = True
# ACCOUNT_USERNAME_REQUIRED = 


# ACCOUNT_USERNAME_REQUIRED = False

# Adding Email Verification for New User Registration

# Email verification settings
ACCOUNT_EMAIL_VERIFICATION = "mandatory"  # Options: "none", "optional", "mandatory"
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_SUBJECT_PREFIX = "DeltaX - "

# Email backend configuration (for development)
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'  # For development
# For production, use SMTP:
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_HOST = 'smtp.your-email-provider.com'
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True
# EMAIL_HOST_USER = 'your-email@example.com'
# EMAIL_HOST_PASSWORD = 'your-email-password'
# Ajoute ceci :
ACCOUNT_SIGNUP_FIELDS = ['email*', 'password1*', 'password2*']

# Add the new recommended setting
ACCOUNT_LOGIN_METHODS = ['email']  # Use the new setting instead of AUTHENTICATION_METHOD

ACCOUNT_EMAIL_CONFIRMATION_URL = f'{FRONTEND_URL}/confirm-email/{{key}}'

# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')


# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'public/static')

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# CORS settings
# CORS_ALLOW_ALL_ORIGINS = True  # For development only, restrict in production
CORS_ALLOW_CREDENTIALS = True  # Allow credentials (cookies, auth tokens, etc.)

# Add this to your settings.py file
FORCE_SCRIPT_NAME = ''
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

# Make sure these are set correctly
ALLOWED_HOSTS = ['deltaxbackend.atcdz.com', 'www.deltaxbackend.atcdz.com','https://www.deltax.atcdz.com']
