import os
from pathlib import Path
from datetime import timedelta
from dotenv import load_dotenv
import pymysql
pymysql.install_as_MySQLdb()
from corsheaders.defaults import default_headers

load_dotenv()

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get('SECRET_KEY', 'dev-secret')
DEBUG = os.environ.get('DEBUG', 'True') == 'True'
ALLOWED_HOSTS = ['*']
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'catalog_app',
    'store',
    'inventory',
    'system_logs',
    'corsheaders',
    'django_icon_picker',
    'ckeditor',
]

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

CORS_ALLOW_ALL_ORIGINS = False

CORS_ALLOWED_ORIGINS = [
    "https://test.taiafropress.com",
    "https://taiafropress.com",
    "https://shop.taiafropress.com",
    "https://testshop.taiafropress.com",
    "http://localhost:8080",
    "http://localhost:3000",
]

CORS_ALLOW_HEADERS = list(default_headers) + [
    "content-type",
]

ROOT_URLCONF = 'rights_catalog.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'rights_catalog.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST', 'db'),
        'PORT': os.getenv('DB_PORT', '3306'),
        'OPTIONS': {
            'init_command': "SET time_zone='+03:00';",
            'sql_mode': 'STRICT_TRANS_TABLES',
        },
    }
}
# Second connection to the same database, used only by the System Log so its
# entries commit independently of (and survive rollback of) the operation
# being logged. See system_logs/routers.py.
DATABASES['logs'] = {**DATABASES['default'], 'TEST': {'MIRROR': 'default'}}
DATABASE_ROUTERS = ['system_logs.routers.SystemLogRouter']

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 = 'en-us'
TIME_ZONE = 'Africa/Nairobi'
USE_I18N = True
USE_TZ = False
STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# DRF + JWT
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ),
}

from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
}

# settings.py

# ---------------------------------------------------------------------------
# Session (required for guest cart support)
# ---------------------------------------------------------------------------
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
SESSION_COOKIE_AGE = 60 * 60 * 24 * 30          # 30 days
SESSION_SAVE_EVERY_REQUEST = False
# Allow cross-origin session cookies so the React frontend can share sessions
SESSION_COOKIE_SAMESITE = 'Lax' if DEBUG else 'None'  # 'None' requires HTTPS (production only)
SESSION_COOKIE_SECURE = not DEBUG                     # Must be True in production (HTTPS)
CORS_ALLOW_CREDENTIALS = True                     # Required for session cookies cross-origin

# ---------------------------------------------------------------------------
# M-Pesa / Daraja API
# ---------------------------------------------------------------------------
MPESA_CONSUMER_KEY = os.getenv('MPESA_CONSUMER_KEY', '')
MPESA_CONSUMER_SECRET = os.getenv('MPESA_CONSUMER_SECRET', '')
MPESA_SHORTCODE = os.getenv('MPESA_SHORTCODE', '174379')   # Sandbox default
MPESA_PASSKEY = os.getenv('MPESA_PASSKEY', '')
# Full HTTPS URL that Safaricom will POST callbacks to
MPESA_CALLBACK_URL = os.getenv(
    'MPESA_CALLBACK_URL',
    'https://api.taiafropress.com/api/payments/mpesa/callback/',
)
# True = use sandbox.safaricom.co.ke  /  False = use api.safaricom.co.ke (production)
MPESA_SANDBOX = os.getenv('MPESA_SANDBOX', 'True') == 'True'
# True = skip real HTTP calls; return mock responses (local dev / CI)
MOCK_MPESA = os.getenv('MOCK_MPESA', 'False') == 'True'
# Master switch for STK ("prompt on phone") payments, store and POS. Off until
# go-live: prompt endpoints refuse requests and the POS shows the option greyed.
MPESA_STK_ENABLED = os.getenv('MPESA_STK_ENABLED', 'False') == 'True'

# Public URL used for absolute links in emails (logo, receipt links) — this
# backend/admin's own domain.
SITE_URL = os.getenv('SITE_URL', 'https://tai.octavestudioske.com')

# The storefront's public URL — used for author/customer-facing links emailed
# from the backend (e.g. the legacy-invitation signing link), which live on
# the Next.js store app, not this Django backend. Override in .env with
# http://localhost:3000 for local dev against a locally-running store.
PUBLIC_STORE_URL = os.getenv('PUBLIC_STORE_URL', 'https://shop.taiafropress.com')

# ---------------------------------------------------------------------------
# Email (Zoho Mail SMTP — see .env for credentials)
# ---------------------------------------------------------------------------
EMAIL_BACKEND = os.getenv('EMAIL_BACKEND', 'django.core.mail.backends.smtp.EmailBackend')
EMAIL_HOST = os.getenv('EMAIL_HOST', 'smtp.zoho.com')
EMAIL_PORT = int(os.getenv('EMAIL_PORT', '587'))
EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS', 'True') == 'True'
EMAIL_USE_SSL = os.getenv('EMAIL_USE_SSL', 'False') == 'True'
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER', '')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD', '')
# Without this, a hung SMTP connection can stall a request (or a newsletter
# send chunk) indefinitely instead of failing fast.
EMAIL_TIMEOUT = int(os.getenv('EMAIL_TIMEOUT', '30'))
DEFAULT_FROM_NAME = os.getenv('DEFAULT_FROM_NAME', 'TAI AfroPress')
DEFAULT_FROM_ADDRESS = os.getenv('DEFAULT_FROM_EMAIL', 'no-reply@taiafropress.com')
DEFAULT_FROM_EMAIL = f'{DEFAULT_FROM_NAME} <{DEFAULT_FROM_ADDRESS}>'
# Monitored inbox shown to customers as "reach us at ..." — must differ from
# DEFAULT_FROM_EMAIL, which is a no-reply sender nobody reads.
SUPPORT_CONTACT_EMAIL = os.getenv('SUPPORT_CONTACT_EMAIL', 'orders@taiafropress.com')

# Newsletter bulk-send pacing — tunable without a redeploy if Zoho throttles.
NEWSLETTER_SEND_CHUNK_SIZE = int(os.getenv('NEWSLETTER_SEND_CHUNK_SIZE', '40'))
NEWSLETTER_SEND_PAUSE_SECONDS = float(os.getenv('NEWSLETTER_SEND_PAUSE_SECONDS', '2'))

# Trimmed CKEditor toolbar for the newsletter composer's Rich Text block —
# bold/italic/links/lists only, no image/table/source-HTML buttons (those
# are separate, purpose-built blocks). Output still goes through
# newsletter_service.sanitize_block_html() before storage regardless.
CKEDITOR_CONFIGS = {
    'default': {},
    'newsletter_richtext': {
        'toolbar': [['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink']],
        'removePlugins': 'elementspath',
        'resize_enabled': False,
        'height': 160,
    },
}

# ---------------------------------------------------------------------------
# System Log & logging
# ---------------------------------------------------------------------------
# Who gets payment-error alert emails (comma-separated). Empty → the Paybill
# settings' admin notification email, then EMAIL_HOST_USER.
SYSTEM_ALERT_EMAILS = [e.strip() for e in os.getenv('SYSTEM_ALERT_EMAILS', '').split(',') if e.strip()]
SYSTEM_LOG_RETENTION_DAYS = int(os.getenv('SYSTEM_LOG_RETENTION_DAYS', '183'))   # ~6 months
SYSTEM_LOG_ASYNC_ALERTS = True
# Used to build "open in admin" links in alert emails.
ADMIN_BASE_URL = os.getenv('ADMIN_BASE_URL', 'https://tai.octavestudioske.com')

# Log files rotate at 5 MB, keeping 5 old files → at most ~30 MB on disk.
LOG_DIR = BASE_DIR / 'logs'
LOG_DIR.mkdir(exist_ok=True)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {'format': '%(asctime)s %(levelname)s %(name)s: %(message)s'},
    },
    'handlers': {
        'console': {'class': 'logging.StreamHandler', 'formatter': 'standard', 'level': 'WARNING'},
        'file': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': str(LOG_DIR / 'app.log'),
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 5,
            'encoding': 'utf-8',
            'formatter': 'standard',
            'level': 'INFO',
        },
        # ERRORs from app code / unhandled request errors also land in the
        # System Log admin page.
        'system_log': {'class': 'system_logs.handlers.SystemLogHandler', 'level': 'ERROR'},
    },
    'loggers': {
        'system_logs': {'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': False},
        'store': {'handlers': ['file', 'console', 'system_log'], 'level': 'INFO', 'propagate': False},
        'inventory': {'handlers': ['file', 'console', 'system_log'], 'level': 'INFO', 'propagate': False},
        'catalog_app': {'handlers': ['file', 'console', 'system_log'], 'level': 'INFO', 'propagate': False},
        'django.request': {'handlers': ['file', 'console', 'system_log'], 'level': 'ERROR', 'propagate': False},
        'django': {'handlers': ['file', 'console'], 'level': 'WARNING', 'propagate': False},
    },
}

