import os
from pathlib import Path
from datetime import timedelta
from dotenv import load_dotenv

BASE_DIR = Path(__file__).resolve().parent.parent

# Load environment variables
env_path = BASE_DIR / '..' / '.env'
if env_path.exists():
    load_dotenv(env_path)

# ============================================
# SECURITY SETTINGS
# ============================================

# SECRET_KEY - MUST be set in .env file
SECRET_KEY = os.getenv('SECRET_KEY')
if not SECRET_KEY:
    raise ValueError("SECRET_KEY must be set in .env file")

# DEBUG - NEVER True in production
DEBUG = True

# ALLOWED_HOSTS - Specify exact domains
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', 'www.adminbackend.com.zionhotel.co.ke').split(',')
if not ALLOWED_HOSTS or ALLOWED_HOSTS == ['']:
    raise ValueError("ALLOWED_HOSTS must be set in .env file")

# ============================================
# CORS SETTINGS - SECURE CONFIGURATION
# ============================================

# Remove CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_ALL_ORIGINS = False  # ✅ Secure

# Only allow specific origins
CORS_ALLOWED_ORIGINS = [
    "https://adminbackend.com.zionhotel.co.ke",
    "www.adminbackend.com.zionhotel.co.ke",
    "https://www.simwaktraders.co.ke"
    # Add your mobile app domains if using web views
]

# For mobile apps using native requests
CORS_ALLOW_CREDENTIALS = True

# ============================================
# DATABASE - USE ENVIRONMENT VARIABLES
# ============================================

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.getenv('DB_NAME'),
        'USER': os.getenv('DB_USER'),
        'PASSWORD': os.getenv('DB_PASSWORD'),
        'HOST': os.getenv('DB_HOST', 'localhost'),
        'PORT': os.getenv('DB_PORT', '5432'),
    }
}

# Validate database settings
if not all([
    os.getenv('DB_NAME'),
    os.getenv('DB_USER'),
    os.getenv('DB_PASSWORD')
]):
    raise ValueError("Database credentials must be set in .env file")

# ============================================
# INSTALLED APPS
# ============================================

INSTALLED_APPS = [
    'corsheaders',
    'core',
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

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',
]

# ============================================
# SECURITY MIDDLEWARE SETTINGS
# ============================================

if not DEBUG:
    # Force HTTPS
    SECURE_SSL_REDIRECT = True
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True
    
    # HSTS Settings
    SECURE_HSTS_SECONDS = 31536000  # 1 year
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True
    
    # Additional security
    SECURE_CONTENT_TYPE_NOSNIFF = True
    SECURE_BROWSER_XSS_FILTER = True
    X_FRAME_OPTIONS = 'DENY'

ROOT_URLCONF = 'storekeeping.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'storekeeping.wsgi.application'

# ============================================
# PASSWORD VALIDATION
# ============================================

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {
            'min_length': 10,  # Stronger minimum
        }
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# ============================================
# INTERNATIONALIZATION
# ============================================

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Nairobi'
USE_I18N = True
USE_TZ = True

# ============================================
# STATIC FILES
# ============================================

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# ============================================
# REST FRAMEWORK - SECURE CONFIGURATION
# ============================================

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    # Rate limiting
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle'
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '100/hour',
        'user': '500/hour'
    }
}

# ============================================
# JWT SETTINGS - SECURE CONFIGURATION
# ============================================

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=90),  # 3 months
    'REFRESH_TOKEN_LIFETIME': timedelta(days=90),  # same as access, optional
    'ROTATE_REFRESH_TOKENS': False,                # optional since access lasts long
    'BLACKLIST_AFTER_ROTATION': True,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'UPDATE_LAST_LOGIN': True,
}

# ============================================
# JAZZMIN SETTINGS (Keep your existing config)
# ============================================

JAZZMIN_SETTINGS = {
    # Site branding
    "site_title": "AdminPOS",
    "site_header": "AdminPOS",
    "site_brand": "AdminPOS",
    "site_logo": None,  # Path to your logo: "images/logo.png"
    "login_logo": None,  # Logo for login page
    "site_logo_classes": "img-circle",
    
    # Welcome text
    "welcome_sign": "Welcome to AdminPOS",
    "copyright": "AdminPOS © 2025",
    
    # Search bar
    "search_model": ["auth.User", "auth.Group"],
    
    # User menu
    "usermenu_links": [
        {"name": "Support", "url": "https://github.com/yourproject", "new_window": True},
        {"model": "auth.user"},
    ],
    
    # Top menu links
    "topmenu_links": [
        {"name": "Home", "url": "admin:index", "permissions": ["auth.view_user"]},
        {"name": "Support", "url": "https://github.com/yourproject", "new_window": True},
    ],

    # Side menu configuration
    "show_sidebar": True,
    "navigation_expanded": True,
    "hide_apps": [],
    "hide_models": [],
    
    # Order apps and models
    "order_with_respect_to": [
        "auth",
        "core",  # Your main app
    ],
    
    # Custom app icons (FontAwesome 5)
    "icons": {
        "auth": "fas fa-users-cog",
        "auth.user": "fas fa-user",
        "auth.Group": "fas fa-users",
        
        # Your core app icons
        "core": "fas fa-store",
        "core.Transaction": "fas fa-receipt",
        "core.Product": "fas fa-box",
        "core.Customer": "fas fa-user-circle",
        "core.Order": "fas fa-shopping-bag",
        "core.Payment": "fas fa-credit-card",
        "core.Category": "fas fa-tags",
        "core.Inventory": "fas fa-warehouse",
        "core.Sale": "fas fa-cash-register",
    },
    
    # Default icons
    "default_icon_parents": "fas fa-chevron-circle-right",
    "default_icon_children": "fas fa-circle",

    # Related modal
    "related_modal_active": False,

    # Custom links in sidebar
    "custom_links": {
        "core": [  # Your app label
            {
                "name": "Dashboard",
                "url": "/admin/dashboard/",  # Direct URL
                "icon": "fas fa-tachometer-alt",
            },
        ]
    },

    # UI Customizer
    "show_ui_builder": False,

    # Change view settings
    "changeform_format": "horizontal_tabs",
    "changeform_format_overrides": {
        "auth.user": "collapsible",
        "auth.group": "vertical_tabs",
    },
}

# Media files (uploads)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# ============================================
# THEME SELECTION - Choose ONE of these
# ============================================
'''
# OPTION 1: Light Modern Theme (RECOMMENDED)
JAZZMIN_UI_TWEAKS = {
    "theme": "flatly",
    "navbar": "navbar-white navbar-light",
    "navbar_fixed": True,
    "sidebar": "sidebar-light-primary",
    "sidebar_nav_compact_style": True,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": True,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": True,
    "brand_color": "navbar-light",
    "brand_small_text": False,
    "accent": "accent-primary",
    "body_small_text": False,
    "footer_small_text": False,
    "button_classes": {
        "primary": "btn-primary",
        "secondary": "btn-secondary",
        "info": "btn-info",
        "warning": "btn-warning",
        "danger": "btn-danger",
        "success": "btn-success"
    },
    "actions_sticky_top": True,
}
'''

# OPTION 2: Dark Theme
# Uncomment this block and comment out OPTION 1 above to use dark theme
"""
JAZZMIN_UI_TWEAKS = {
    "theme": "darkly",
    "navbar": "navbar-dark navbar-gray-dark",
    "navbar_fixed": True,
    "sidebar": "sidebar-dark-primary",
    "sidebar_nav_compact_style": True,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": True,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": True,
    "brand_color": "navbar-dark",
    "brand_small_text": False,
    "accent": "accent-info",
    "body_small_text": False,
    "footer_small_text": False,
    "button_classes": {
        "primary": "btn-primary",
        "secondary": "btn-secondary",
        "info": "btn-info",
        "warning": "btn-warning",
        "danger": "btn-danger",
        "success": "btn-success"
    },
    "actions_sticky_top": True,
}
"""


# OPTION 3: Purple/Luxury Theme
# Uncomment this block and comment out OPTION 1 above to use purple theme

JAZZMIN_UI_TWEAKS = {
    "theme": "spacelab",
    "navbar": "navbar-white navbar-light",
    "navbar_fixed": True,
    "sidebar": "sidebar-light-primary",
    "sidebar_nav_compact_style": True,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": True,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": True,
    "brand_color": "navbar-primary",
    "brand_small_text": False,
    "accent": "accent-purple",
    "body_small_text": False,
    "footer_small_text": False,
    "button_classes": {
        "primary": "btn-primary",
        "secondary": "btn-secondary",
        "info": "btn-info",
        "warning": "btn-warning",
        "danger": "btn-danger",
        "success": "btn-success"
    },
    "actions_sticky_top": True,
}



# OPTION 4: Gradient/Modern Theme (With Custom CSS)
# Uncomment this block and comment out OPTION 1 above to use gradient theme
"""
JAZZMIN_UI_TWEAKS = {
    "theme": "materia",
    "navbar": "navbar-white navbar-light",
    "navbar_fixed": True,
    "sidebar": "sidebar-light-info",
    "sidebar_nav_compact_style": True,
    "sidebar_nav_legacy_style": False,
    "sidebar_nav_flat_style": True,
    "sidebar_disable_expand": False,
    "sidebar_nav_child_indent": True,
    "brand_color": "navbar-info",
    "brand_small_text": False,
    "accent": "accent-info",
    "body_small_text": False,
    "footer_small_text": False,
    "button_classes": {
        "primary": "btn-primary",
        "secondary": "btn-secondary",
        "info": "btn-info",
        "warning": "btn-warning",
        "danger": "btn-danger",
        "success": "btn-success"
    },
    "actions_sticky_top": True,
}
"""

# ============================================
# LOGGING - Monitor security events
# ============================================

# Create logs directory if it doesn't exist
LOGS_DIR = os.path.join(BASE_DIR, 'logs')
os.makedirs(LOGS_DIR, exist_ok=True)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGS_DIR, 'security.log'),
            'formatter': 'verbose',
        },
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django.security': {
            'handlers': ['file', 'console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}