import os
from datetime import timedelta
from pathlib import Path

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

SECRET_KEY = 'django-insecure-your-secret-key-here'

DEBUG = True

ALLOWED_HOSTS = ['*']
# Celery / Redis
REDIS_URL = os.getenv('REDIS_URL', 'redis://127.0.0.1:6379/0')
CELERY_BROKER_URL = REDIS_URL
CELERY_RESULT_BACKEND = REDIS_URL
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Europe/Helsinki'
# Ensure Celery explicitly imports ML service tasks so workers register them
CELERY_IMPORTS = (
    'ml_service.tasks',
)

CELERY_BEAT_SCHEDULE = {
    'catch-up-balances-frequent': {
        'task': 'worktimeservice.tasks.schedule_catch_up_balance',
        # Schedule to run every 5 minutes for near real-time reconciliation.
        'schedule': timedelta(minutes=5),
    },
    'schedule-daily-notifications': {
        'task': 'ml_service.tasks.schedule_daily_notifications',
        'schedule': timedelta(hours=24),  # Daily at midnight
    },
    'cleanup-old-scheduled-notifications': {
        'task': 'ml_service.tasks.cleanup_old_scheduled_notifications',
        'schedule': timedelta(days=1),  # Daily cleanup
    },
    'analyze-burnout-daily': {
        'task': 'ml_service.tasks.analyze_burnout_daily',
        'schedule': timedelta(hours=24),  # Daily at 6 PM
    },
}
FIREBASE_SERVICE_ACCOUNT_KEY = os.path.join(BASE_DIR, 'firebase-service-account.json')
FIREBASE_PROJECT_ID = 'flexwise-2f2e8'
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'paycode',
    'functions',
    'shift',
    'configurations',
    'questionconfigurations',
    'ErrorLogs',
    'user',
    'userSettings',
    'stamps',
    'balances',
    'supervisor',
    'supervisorgroup',
    'employeetypes',
    'company',
    'worktimeservice',
    'balancedetail',
    'ml_service',
    'projects',
    'tasks',
    'clients',
    'payroll',
]

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

ROOT_URLCONF = 'worktimeapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'worktimeapp.wsgi.application'

# Database configuration
# Uses external MySQL server (configured via environment variables)
# Also supports SQLite for migration purposes
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('MYSQL_DATABASE', 'master_timestamp'),
        'USER': os.getenv('MYSQL_USER', 'root'),
        'PASSWORD': os.getenv('MYSQL_PASSWORD', 'test'),
        'HOST': os.getenv('MYSQL_HOST', '86.105.252.92'),
        'PORT': os.getenv('MYSQL_PORT', '3306'),
        'OPTIONS': {
            'charset': 'utf8mb4',
            #'init_command': "SET sql_mode='STRICT_TRANS_TABLES', SESSION max_allowed_packet=67108864",  # 64MB
        },
    },
    # SQLite database for migration (only used during data migration)
    'sqlite': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Override Django's MySQL version check to support MySQL 5.7
# Django 5.0 requires MySQL 8.0.11+, but we need to support MySQL 5.7.42
from django.db.backends.mysql.base import DatabaseWrapper
original_check_database_version_supported = DatabaseWrapper.check_database_version_supported

def patched_check_database_version_supported(self):
    """Override to allow MySQL 5.7"""
    pass  # Skip version check

DatabaseWrapper.check_database_version_supported = patched_check_database_version_supported

# If MySQL is not available, fallback to SQLite (for local development without Docker)
if os.getenv('USE_SQLITE', 'False').lower() == 'true':
    DATABASES['default'] = DATABASES['sqlite']

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 = 'UTC'
USE_I18N = True
USE_TZ = True

STATIC_URL = 'static/'

CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = [
    'http://localhost',
    'http://localhost:3000',
    'http://localhost:5174',
    'http://127.0.0.1:3000',
    'http://192.168.1.110:5174',
    'http://0.0.0.0:5174',
]
CORS_ALLOW_CREDENTIALS = True

# Make sure Authorization is accepted and exposed
CORS_ALLOW_HEADERS = list(set([
    'authorization',
    'content-type',
    'accept',
    'origin',
    'user-agent',
    'dnt',
    'cache-control',
    'x-requested-with',
]))
CORS_EXPOSE_HEADERS = ['Authorization']

# CSRF for cookie-based auth when needed
CSRF_TRUSTED_ORIGINS = [
    'http://localhost',
    'http://localhost:3000',
    'http://localhost:5174',
    'http://127.0.0.1:3000',
    'http://192.168.1.110:5174',
    'http://0.0.0.0:5174',
]

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'worktimeapp.jwt_auth.UUIDJWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
} 

# Simple JWT configuration
from datetime import timedelta as _jwt_timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': _jwt_timedelta(minutes=30),
    'REFRESH_TOKEN_LIFETIME': _jwt_timedelta(days=30),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',  # Use 'id' field (which is UUIDField)
    'USER_ID_CLAIM': 'user_id',  # The claim in the token that contains the user ID
    'TOKEN_USER_CLASS': 'user.models.User',  # Use custom User model
}

# Logging configuration
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',  # Show INFO level and above
    },
    'loggers': {
        'configurations': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django': {
            'handlers': ['console'],
            'level': 'WARNING',  # Only show warnings and errors for Django itself
            'propagate': False,
        },
    },
}