import os
from decouple import config
from pathlib import Path

import pymysql
pymysql.install_as_MySQLdb()


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


DEBUG = config("DEBUG")
ALLOWED_HOSTS = ["*"]
SECRET_KEY = config("DJANGO_SECRET_KEY")

# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.sites",
    
    'maintenance_mode',
    'django_bootstrap5',
    "django_htmx",
    'django_ckeditor_5', 
    "crispy_forms",
    "crispy_bootstrap5",
    
    'allauth',
    'allauth.account',
    # The MFA app:
    'allauth.mfa',

    # Optional -- requires install using `django-allauth[socialaccount]`.
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.twitter',
    'allauth.socialaccount.providers.instagram',
    'allauth.socialaccount.providers.yahoo',
    'allauth.socialaccount.providers.microsoft',

    'core',
    "users",
]

CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
CRISPY_TEMPLATE_PACK = "bootstrap5"

SITE_ID = 1
# ALLAUTH_UI_THEME = "dark"

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    
    "django.contrib.messages.middleware.MessageMiddleware",
    'allauth.account.middleware.AccountMiddleware',

    "django.middleware.clickjacking.XFrameOptionsMiddleware",    
    "django_htmx.middleware.HtmxMiddleware",
    "maintenance_mode.middleware.MaintenanceModeMiddleware",
]

ROOT_URLCONF = "celebrity.urls"

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",
                "core.context_processors.notifications",
            ],
        },
    },
]

WSGI_APPLICATION = "celebrity.wsgi.application"


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": "dsncoetw_cerebrity_db",
        'USER': 'dsncoetw_celebrity_users',
        "PASSWORD": "F%QXI68,z81SDDu]",
        "HOST": "127.0.0.1",  # Use 127.0.0.1 instead of localhost
        "PORT": "3306",
        'OPTIONS': {
             "charset": "utf8mb4",
            "init_command": "SET sql_mode='STRICT_TRANS_TABLES'",
            'init_command': 'SET default_storage_engine=INNODB',
            'init_command': "SET sql_mode='NO_AUTO_VALUE_ON_ZERO';",
        }
    }
}
# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

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",
    },
]


AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]

# 🚦 Rate limits for authentication-related actions
ACCOUNT_RATE_LIMITS = {
    # 🔑 Login attempts
    "login_failed": "5/5m",         # Max 5 failed logins in 5 minutes per IP/user
    # "login_success": "20/1h",       # Optional: Limit total logins per hour

    # 📝 Signup
    "signup": "3/h",                # Max 3 new signups per hour per IP
    "verify_email": "5/h",          # Max 5 verification emails per hour per user

    # 🔄 Password reset
    "password_reset": "3/h",        # Max 3 reset emails per hour
    "password_reset_verify": "5/h",  # Max 5 reset attempts per hour

    # 📧 Email confirmation resend
    "email_confirmation": "3/h",    # Max 3 resends per hour per email

    # (Optional) Social login attempts
    "social_login": "10/1h",        # Max 10 social logins per hour
}

# Redirect URLs
LOGIN_REDIRECT_URL = "/"  # temporary placeholder
LOGOUT_REDIRECT_URL = '/'  # After logout

ACCOUNT_SIGNUP_REDIRECT_URL = "account_login"

# Optional account settings
ACCOUNT_LOGIN_METHODS = {"username"}   # login with username
ACCOUNT_EMAIL_MAX_LENGTH = 255

ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_SIGNUP_FIELDS = ['email*', 'username*', 'password1*', 'password2*']
ACCOUNT_EMAIL_VERIFICATION = "mandatory"  # "mandatory", "optional", "none"

SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_STORE_TOKENS = True
SOCIALACCOUNT_AUTO_SIGNUP = True


SOCIALACCOUNT_PROVIDERS = {
    "google": {
        "APP": {
            "client_id": config("GOOGLE_CLIENT_ID"),
            "secret": config("GOOGLE_CLIENT_SECRET"),
            "key": "",
        },
        "SCOPE": ["profile", "email"],
        "AUTH_PARAMS": {"access_type": "online"},
        "OAUTH_PKCE_ENABLED": True,
    },
    
    "yahoo": {
        "APP": {
            "client_id": config("YAHOO_CLIENT_ID"),
            "secret": config("YAHOO_CLIENT_SECRET"),
            "key": "",
        },
        "SCOPE": ["openid", "profile", "email"],
    },
    
    "facebook": {
        "APP": {
            "client_id": config("FACEBOOK_CLIENT_ID"),
            "secret": config("FACEBOOK_CLIENT_SECRET"),
            "key": "",
        },
        "METHOD": "oauth2",
        "SCOPE": ["email", "public_profile"],
        "AUTH_PARAMS": {"auth_type": "reauthenticate"},
        "FIELDS": [
            "id", "first_name", "last_name", "email", "picture"
        ],
        "EXCHANGE_TOKEN": True,
        "VERSION": "v13.0",
    },
    
    "twitter": {   # Note: Twitter (X) often needs special handling
        "APP": {
            "client_id": config("CONSUMER_KEY"),      # Twitter API Key
            "secret": config("CONSUMER_SECRETE"),     # Twitter API Secret
            "key": "",
        },
    },
    
    "instagram": {
        "APP": {
            "client_id": config("INSTAGRAM_CLIENT_ID"),
            "secret": config("INSTAGRAM_CLIENT_SECRET"),
            "key": "",
        },
    },
    
    "microsoft": {
        "APP": {
            "client_id": config("MICROSOFT_CLIENT_ID"),
            "secret": config("MICROSOFT_CLIENT_SECRET"),
            "key": "",
        },
        "settings": {
            "tenant": "organizations",
            "login_url": "https://login.microsoftonline.com",
            "graph_url": "https://graph.microsoft.com",
        }
    }
}


AUTH_USER_MODEL = "users.CustomUser"

# Payment provider configuration
STRIPE_SECRET_KEY = config("STRIPE_SECRET_KEY", default="")
STRIPE_PUBLISHABLE_KEY = config("STRIPE_PUBLISHABLE_KEY", default="")
PAYSTACK_SECRET_KEY = config("PAYSTACK_SECRET_KEY", default="")
PAYSTACK_PUBLIC_KEY = config("PAYSTACK_PUBLIC_KEY", default="")
FLUTTERWAVE_SECRET_KEY = config("FLUTTERWAVE_SECRET_KEY", default="")
FLUTTERWAVE_PUBLIC_KEY = config("FLUTTERWAVE_PUBLIC_KEY", default="")

# Email configuration
SECURE_HSTS_SECONDS = 31536000  # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# Email settings
EMAIL_BACKEND = config("EMAIL_BACKEND")
EMAIL_HOST = config("EMAIL_HOST", default="")
EMAIL_PORT = config("EMAIL_PORT", default=587, cast=int)
EMAIL_USE_TLS = config("EMAIL_USE_TLS", default=True, cast=bool)
EMAIL_HOST_USER = config("EMAIL_HOST_USER", default="")
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD", default="")
DEFAULT_FROM_EMAIL = config("DEFAULT_FROM_EMAIL", default="celebrity@banshix.com")

MFA_FORMS = {
    'authenticate': 'allauth.mfa.base.forms.AuthenticateForm',
    'reauthenticate': 'allauth.mfa.base.forms.AuthenticateForm',
    'activate_totp': 'allauth.mfa.totp.forms.ActivateTOTPForm',
    'deactivate_totp': 'allauth.mfa.totp.forms.DeactivateTOTPForm',
    'generate_recovery_codes': 'allauth.mfa.recovery_codes.forms.GenerateRecoveryCodesForm',
}

# Make sure "webauthn" is included.
MFA_SUPPORTED_TYPES = ["totp", "webauthn", "recovery_codes"]
# Optional: enable support for logging in using a (WebAuthn) passkey.
MFA_PASSKEY_LOGIN_ENABLED = True
# Optional -- use for local development only: the WebAuthn uses the
# ``fido2`` package, and versions up to including version 1.1.3 do not
# regard localhost as a secure origin, which is problematic during
# local development and testing.
MFA_WEBAUTHN_ALLOW_INSECURE_ORIGIN = True
# Turn on/off manually
MAINTENANCE_MODE = False
# Who can bypass maintenance mode
MAINTENANCE_MODE_IGNORE_SUPERUSER = True
# MAINTENANCE_MODE_IGNORE_STAFF = True
# MAINTENANCE_MODE_IGNORE_IP_ADDRESSES = ['127.0.0.1']

# Custom template
MAINTENANCE_MODE_TEMPLATE = 'errors/503.html'


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = "static/"

# This is where your custom static files (like JS) live
STATICFILES_DIRS = [BASE_DIR / "static",]

# This is where static files will be collected for production
STATIC_ROOT = BASE_DIR / "staticfiles"

MEDIA_URL = '/media/'  # URL to access media files
MEDIA_ROOT = BASE_DIR / 'media'  # Directory where media files are uploaded

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

customColorPalette = [
        {
            'color': 'hsl(4, 90%, 58%)',
            'label': 'Red'
        },
        {
            'color': 'hsl(340, 82%, 52%)',
            'label': 'Pink'
        },
        {
            'color': 'hsl(291, 64%, 42%)',
            'label': 'Purple'
        },
        {
            'color': 'hsl(262, 52%, 47%)',
            'label': 'Deep Purple'
        },
        {
            'color': 'hsl(231, 48%, 48%)',
            'label': 'Indigo'
        },
        {
            'color': 'hsl(207, 90%, 54%)',
            'label': 'Blue'
        },
    ]

# CKEditor 5 Configuration
CKEDITOR_5_CONFIGS = {
    'default': {
        'toolbar': ['heading', '|', 'bold', 'italic', 'link',
                   'bulletedList', 'numberedList', 'blockQuote', 'imageUpload', ],
    },
    'extends': {
        'blockToolbar': [
            'paragraph', 'heading1', 'heading2', 'heading3',
            '|',
            'bulletedList', 'numberedList',
            '|',
            'blockQuote',
        ],
        'toolbar': ['heading', '|', 'outdent', 'indent', '|', 'bold', 'italic', 'link', 'underline', 'strikethrough',
                   'code','subscript', 'superscript', 'highlight', '|', 'codeBlock', 'sourceEditing', 'insertImage',
                    'bulletedList', 'numberedList', 'todoList', '|',  'blockQuote', 'imageUpload', '|',
                    'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', 'mediaEmbed', 'removeFormat',
                    'insertTable',],
        'image': {
            'toolbar': ['imageTextAlternative', '|', 'imageStyle:alignLeft',
                        'imageStyle:alignRight', 'imageStyle:alignCenter', 'imageStyle:side',  '|'],
            'styles': [
                'full',
                'side',
                'alignLeft',
                'alignRight',
                'alignCenter',
            ]

        },
        'table': {
            'contentToolbar': [ 'tableColumn', 'tableRow', 'mergeTableCells',
            'tableProperties', 'tableCellProperties' ],
            'tableProperties': {
                'borderColors': customColorPalette,
                'backgroundColors': customColorPalette
            },
            'tableCellProperties': {
                'borderColors': customColorPalette,
                'backgroundColors': customColorPalette
            }
        },
        'heading' : {
            'options': [
                { 'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph' },
                { 'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1' },
                { 'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2' },
                { 'model': 'heading3', 'view': 'h3', 'title': 'Heading 3', 'class': 'ck-heading_heading3' }
            ]
        }
    },
    'list': {
        'properties': {
            'styles': 'true',
            'startIndex': 'true',
            'reversed': 'true',
        }
    }
}




