from pathlib import Path
import os

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

SECRET_KEY = 'django-insecure-=s93t5$8-3p$r_+amhwsg2!&+2^q(c_dfd-4l--j%^_2^tb(ym'

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 'landing',
    'accounts',
    # 'users',
    'users.apps.UsersConfig',  # ✅ not just 'users'
    'geoapi',
    'vouchers',
    'widget_tweaks',
    'recharge',
    'payments',
    'reports',
    'dashboard',
    # 'testapp',
    'notifications',
    'vadmin',
    'commissions',
    'rest_framework',
    'rest_framework.authtoken',
    'drf_yasg',  # ✅ Add this
    'django.contrib.humanize',
    "corsheaders",
    "support",
    "django_filters",
    "geo",




]

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",  # put it high, before CommonMiddleware
    'django.middleware.common.CommonMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',



]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

ROOT_URLCONF = 'viralpe.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': 
        [
            # BASE_DIR / "templates"
            os.path.join(BASE_DIR, 'templates'),  # ✅ Global templates folder
            os.path.join(BASE_DIR, 'vadmin', 'templates', 'vadmin'),  # ✅ Your app-specific templates
            os.path.join(BASE_DIR, 'payments', 'templates', 'payments'),  # ✅ Your app-specific templates
            os.path.join(BASE_DIR, 'commissions', 'templates', 'commissions'),  # ✅ Your app-specific 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',
                'users.context_processors.device_type',  

            ],
        },
    },
]

WSGI_APPLICATION = 'viralpe.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }
# mysql -h viralpe.com -P 3306 -u viralpew_23ubs2ered12d2fbh1 -p -e "SELECT @@version, @@version_comment; SELECT DATABASE();" viralpew_231fb2gbed132fbh1
# mysql -h viralpe.com -P 3306 -u viralpew_23ubs2ered12d2fbh1 -p viralpew_231fb2gbed132fbh1 -e "SHOW COLUMNS FROM payments_viralpewalletusage;"

DATABASES = {
    'default': {
        # 'ENGINE': 'django.db.backends.mysql',
        'ENGINE': 'custom_mysql_backend',
        'NAME': 'viralpew_231fb2gbed132fbh1',       # Database name
        'USER': 'viralpew_23ubs2ered12d2fbh1',       # Database username
        'PASSWORD': 'T0Fq1,sd0PtY',  # Database password
        'HOST': '87.98.244.114',          # Or your DB server IP / domain
        'PORT': '3306',               # Default MySQL port
        "CONN_MAX_AGE": 60,

        # 'OPTIONS': {
        #     'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        #     'charset': 'utf8mb4',
        #     # If your host requires SSL, add:
        #     # 'ssl': {'ssl_mode': 'REQUIRED'},
        # },
        "OPTIONS": {
            "charset": "utf8mb4",
            "init_command": "SET sql_mode='STRICT_TRANS_TABLES'; SET NAMES utf8mb4",
        },
        'TEST': {'CHARSET': 'utf8mb4', 'COLLATION': 'utf8mb4_unicode_ci'},

    }
    
    # T0Fq1,sd0PtY
}
# DATABASES["default"]["OPTIONS"] = {
#     "init_command": "SET sql_mode='STRICT_TRANS_TABLES'; SET NAMES 'utf8mb4' COLLATE 'utf8mb4_unicode_ci'",
# }

# DATABASES['default']['OPTIONS'] = {
#     'init_command': (
#         "SET sql_mode="
#         "'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,"
#         "ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"
#     ),
#     'charset': 'utf8mb4',
# }
# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 4,
        }
    },
    # Comment out or remove these:
    # {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
    # {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'},
    # {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
]

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

# settings.py
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
        "rest_framework_simplejwt.authentication.JWTAuthentication",

    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.AllowAny",  # or IsAuthenticated if most endpoints require login
        "rest_framework.permissions.IsAuthenticated",

    ],
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {
        "anon": "30/min",
        "user": "120/min",
        "reset_pin": "5/min",     # tune to taste

    },
    "DEFAULT_FILTER_BACKENDS": [
        "django_filters.rest_framework.DjangoFilterBackend",
        "rest_framework.filters.SearchFilter",
        "rest_framework.filters.OrderingFilter",
    ],
    # (Optional) global pagination; you can skip since we set per-view
    # "DEFAULT_PAGINATI
    "DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%S.%fZ"  # explicit UTC format

}


# from drf_yasg import openapi

# SWAGGER_SETTINGS = {
#     'SECURITY_DEFINITIONS': {
#         'Token': {
#             'type': 'apiKey',
#             'name': 'Authorization',
#             'in': 'header',
#             'description': 'Use format: Token <your_auth_token>'
#         }
#     }
# }


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

LANGUAGE_CODE = 'en-us'

# TIME_ZONE = 'UTC'
USE_I18N = True

USE_TZ = True
TIME_ZONE = "Asia/Kolkata"


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

STATIC_URL = '/static/'
STATICFILES_DIRS = [ BASE_DIR / "static" ]  # Add this if it doesn't exist
STATIC_ROOT = BASE_DIR / 'staticfiles'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# --------------------------
AUTH_USER_MODEL = 'users.CustomUser'

# 

# import os

# EMAIL_HOST_USER = os.getenv("EMAIL_USER")
# EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASS")

# DEFAULT_FROM_EMAIL = 'noreply@viralpe.com'

# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'



EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.zeptomail.in'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'emailappsmtp.404a316c75e4c5c9'  # ZeptoMail provided username
EMAIL_HOST_PASSWORD = 'ygtF8p4VF9V9'  # 🔐 Replace with actual password

# EMAIL_HOST = 'smtp.gmail.com'
# EMAIL_PORT = 587
# EMAIL_USE_TLS = True
# EMAIL_HOST_USER = 'rajucreations@gmail.com'
# EMAIL_HOST_PASSWORD = 'lzac uavf mdei rlcw'  # Not your Gmail password — use App Password

DEFAULT_FROM_EMAIL = 'Welcome@viralpe.com'  # ✅ Sender Domain


LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/login/'  # or 'home'

# Which provider to use: "a1topup" or "goterpay"
RECHARGE_PROVIDER = "goterpay"
PROVIDER_SOURCE_MAP = {
    "goterpay": "Goter",
    "a1topup": "A1Topup",
}

RECHARGE_PROVIDERS = {
    "a1topup": {
        "base_url": "https://business.a1topup.com/recharge",  # if needed
        "api_key": "505621",
        "api_secret": "6l3xy8me",
        # ...whatever your A1TopupAPI needs
    },
    "goterpay": {
        "mid": "G288696404",
        "mkey": "SHAJ114840",
        #SHAJ947607
        "subwallet": "GVHLO1U1VQINULP8P9UMY",
        # "subwallet": "G9P3EYVCEIB6YK3C59ULK",
        
    },
}
# Where to write cached JSON files (adjust as you like)
PLANS_CACHE_DIR = BASE_DIR / "plans_cache"

A1TOPUP_USERNAME = '505621'
A1TOPUP_PASSWORD = '6l3xy8me'

# Configure Razorpay API Keys
# RAZORPAY_API_KEY = "rzp_live_gjjyMkcuCKnPXM"
# RAZORPAY_API_SECRET = "2j2zFiJhfxsAFC8e8ztlPr1f"

RAZORPAY_API_KEY = "rzp_live_zRbyr3RV2Px7h4"
RAZORPAY_API_SECRET = "vaucYvzWsnOJDjTOBE29RLO9"

# RAZORPAY_API_KEY = "rzp_test_ucG5jUMuux1aHV"
# RAZORPAY_API_SECRET = "M32miEtI8PWz2M67NLVhH6Tg"
RAZORPAY_FEATURE_ENABLED = True  # Toggle Razorpay integration on/off
# context["enable_razorpay"] = settings.ENABLE_RAZORPAY
	
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'
CSRF_TRUSTED_ORIGINS = [
    "https://webapp.viralpe.com",
    "https://vap.proactiveevents.in",
    # "https://8d5737c45559.ngrok-free.app",
    # "https://*.ngrok-free.app",
    "http://localhost:5174",
    "http://127.0.0.1:5174",
    "http://localhost:5173",
    "http://127.0.0.1:5173",
    "http://192.168.29.19:5174",
    "http://192.168.29.19:5174",
    "http://192.168.32.1:5174",

]
CORS_ALLOWED_ORIGINS = [
    "https://webapp.viralpe.com",
    "https://vap.proactiveevents.in",
    # add staging if any, e.g. "https://staging.webapp.viralpe.com"
    # add local dev origins if you want dev to work too
    "http://localhost:5174",
    "http://127.0.0.1:5174",
    "http://localhost:5173",
    "http://127.0.0.1:5173",
    "http://192.168.29.19:5174",
    "http://192.168.32.1:5174",

]
CORS_ALLOW_CREDENTIALS = True



# Optional: allow common headers/methods explicitly
CORS_ALLOW_HEADERS = ["authorization", "content-type", "x-csrftoken", "x-requested-with" ]
CORS_ALLOW_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]

APPEND_SLASH = True

# 43.230.214.211 
# 118.139.176.76

# da03910d-54ea-4c25-9721-e0834903f9fc

# {"pincode": "500095", "city": "Hyderabad", "state": "Telangana", "formatted_address": "Goddess Sri Kanaka Durga Temple, Chowdary Bagh, Badi Chowdi, Ward 78 Gunfoundry, Greater Hyderabad Municipal Corporation Central Zone, Hyderabad, Nampally Mandal, Hyderabad, Telangana, 500095, India", "source": "ola_acc1", "soft_warning": false, "lat": 17.3906, "lon": 78.4874}

import warnings
warnings.filterwarnings("ignore", category=UserWarning, module="razorpay.client")

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# C:\Users\rajuc\Downloads\ngrok-v3-stable-windows-amd64\ngrok http --domain=eaa50994d36d.ngrok-free.app 8888
USE_TZ = True
TIME_ZONE = "Asia/Kolkata"   # for display/admin/templates

# MySQL example (only for MySQL, not SQLite)
if DATABASES['default']['ENGINE'] == 'django.db.backends.mysql':
    DATABASES['default'].setdefault('OPTIONS', {})
    DATABASES['default']['OPTIONS']['init_command'] = "SET time_zone = '+00:00'"


LOG_DIR = os.path.join(BASE_DIR, "logs")
os.makedirs(LOG_DIR, exist_ok=True)

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "handlers": {
        "app_file": {
            "class": "logging.handlers.RotatingFileHandler",
            "filename": os.path.join(LOG_DIR, "app.log"),
            "maxBytes": 5_000_000,  # 5 MB
            "backupCount": 5,
            "encoding": "utf-8",
        },
        "console": {  # goes to server logs (stdout/stderr)
            "class": "logging.StreamHandler",
        },
    },
    "loggers": {
        "": {"handlers": ["app_file", "console"], "level": "INFO"},
        "django": {"handlers": ["app_file"], "level": "INFO", "propagate": False},
    },
}
