from pathlib import Path
import os
from dotenv import load_dotenv
load_dotenv()

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

CHATGPT_API_KEY = os.getenv('CHATGPT_API_KEY')

# Make sure the key exists (optional, for security)
if not CHATGPT_API_KEY:
    raise ValueError("OpenAI API key not found in environment variables")

PAYPAL_CLIENT_ID = os.getenv("PAYPAL_CLIENT_ID")

PAYPAL_CLIENT_SECRET = os.getenv("PAYPAL_CLIENT_SECRET")

PAYPAL_MODE = os.getenv("PAYPAL_MODE", default="sandbox")

# 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!
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY")
STRIPE_PUBLISHABLE_KEY = os.getenv("STRIPE_PUBLISHABLE_KEY")
STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET")

SECRET_KEY = os.environ['DJANGO_SECRET_KEY'] 

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

# Production
#DEBUG = False
#SECURE_COOKIES=True


ALLOWED_HOSTS = ['127.0.0.1']

"""
ALLOWED_HOSTS = [
    "ensolanka.lk",
    "www.ensolanka.lk",
    "203.161.35.222",   # optional, for IP testing
    "127.0.0.1",
    "localhost",
]
"""

#CSRF_TRUSTED_ORIGINS = ["https://ensolanka.lk", "https://www.ensolanka.lk",]


SITE_DOMAIN = '127.0.0.1'
DEFAULT_PROTOCOL = 'http'
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'expat_life.apps.ExpatLifeConfig',
    'rental_app.apps.RentalAppConfig',
    'dating_app.apps.DatingAppConfig',
    'service_partner_app.apps.ServicePartnerAppConfig',
    'affiliates_app.apps.AffiliatesAppConfig',
    'property_manager_app.apps.PropertyManagerAppConfig',
    'hosting_app.apps.HostingAppConfig',
    'myadmin.apps.MyadminConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'affiliates_app.middleware.AffiliateTrackingMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'travel_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'expat_life.context_processors.user_profiles_context',
                'myadmin.context_processors.staff_profile_context',
            ],
        },
    },
]

WSGI_APPLICATION = 'travel_project.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',
    }
}
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        "OPTIONS": {
            "charset": "utf8mb4",
            "use_unicode": True,
            # (Optional) good defaults:
            "init_command": "SET sql_mode='STRICT_TRANS_TABLES', innodb_strict_mode=1",
        },
        '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'),
    }
}
"""

# Password validation
# https://docs.djangoproject.com/en/5.2/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',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.2/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.2/howto/static-files/

STATIC_URL = "static/"
STATICFILES_DIRS = [BASE_DIR / "static"]

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

#LOGIN_REDIRECT_URL = '/dashboard/'
#LOGOUT_REDIRECT_URL = '/'
#LOGIN_URL = '/accounts/login/'

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
LOGIN_URL = '/'

# Email Backend for development
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True

EMAIL_HOST_USER = "dsjayathunge@gmail.com"
EMAIL_HOST_PASSWORD = "mviz amxr uncd rase"

ADMIN_EMAIL = "dsjayathunge@gmail.com"
DEFAULT_FROM_EMAIL = "Ensolanka LLC <dsjayathunge@gmail.com>"

#Email Backend for Production:
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
#EMAIL_HOST = 'business141.web-hosting.com'  #mail.ensolanka.lk'
#EMAIL_PORT = 465
#EMAIL_USE_TLS = False
#EMAIL_USE_SSL = True
#EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
#EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')

#ADMIN_EMAIL = "admin@ensolanka.lk"
#DEFAULT_FROM_EMAIL = "Ensolanka LLC <admin@ensolanka.lk>"

GOOGLE_RECAPTCHA_SECRET_KEY = os.getenv('GOOGLE_RECAPTCHA_SECRET_KEY')
GOOGLE_RECAPTCHA_SITE_KEY = os.getenv('GOOGLE_RECAPTCHA_SITE_KEY')

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
        'django.core.mail': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },
}

"""
# ============================================================
# PRODUCTION SECURITY / SESSION SETTINGS
# ============================================================

# Force HTTPS cookies
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

# Recommended browser cookie protection
SESSION_COOKIE_HTTPONLY = True

# Default is usually Lax, but explicit is better
SESSION_COOKIE_SAMESITE = 'Lax'
CSRF_COOKIE_SAMESITE = 'Lax'

# Store sessions in database
SESSION_ENGINE = 'django.contrib.sessions.backends.db'

# Keep users logged in for 30 days
SESSION_COOKIE_AGE = 30 * 24 * 60 * 60

# Do not expire immediately when browser closes
SESSION_EXPIRE_AT_BROWSER_CLOSE = False

# Optional: only refresh session expiry when session is modified
SESSION_SAVE_EVERY_REQUEST = False

"""

#SITE_DOMAIN =  "https://ensolanka.lk"