import os
import datetime
from typing import Dict, Any
from dotenv import load_dotenv

# Load environment variables
base = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(base, 'config.env'))

class BaseConfig:
    """Base configuration class with common settings."""
    # API Documentation Settings
    API_TITLE = 'KISNAP'
    API_VERSION = '1.0.0'
    OPENAPI_VERSION = '3.0.3'
    OPENAPI_JSON_PATH = 'api-spec.json'
    OPENAPI_URL_PREFIX = '/'
    OPENAPI_REDOC_PATH = '/api/v1/documentation'
    OPENAPI_REDOC_VERSION = 'next'
    OPENAPI_REDOC_URL = (
        'https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js'
    )
    
    API_SPEC_OPTIONS: Dict[str, Any] = {
        'info': {
            'description': """
            # KISNAP Management System Documentation

            ## Overview
            KISNAP Management System is a comprehensive educational platform designed for technical training institutions, providing enterprise-grade tools and services to optimize academic operations, student lifecycle management, and institutional administration.

            ## Key Features
            - **Student Management** - Student registration, enrollment, academic records, and progress tracking
            - **Tutor Management** - Staff profiles, qualifications, schedules, and performance monitoring
            - **Course Management** - Course creation, curriculum design, prerequisites, and academic content
            - **Timetable Management** - Class scheduling, room allocation, and resource coordination
            - **Student Tracking** - Academic progress monitoring, attendance tracking, and performance analytics
            - **Assessment Management** - Exam scheduling, grading systems, and result processing
            - **Academic Reporting** - Student transcripts, institutional analytics, and compliance reports
            - **Communication System** - Notifications, announcements, and parent-student-tutor messaging
            - **Resource Management** - Classroom allocation, equipment tracking, and facility management
            - **Fee Management** - Payment tracking, billing, and financial reporting

            ## Educational Modules
            ### Student Lifecycle Management
            - Admission and enrollment processes
            - Academic progression tracking
            - Graduation and certification management

            ### Academic Operations
            - Course catalog and curriculum management
            - Class scheduling and resource allocation
            - Assessment and examination systems

            ### Administrative Functions
            - Staff management and scheduling
            - Financial tracking and reporting
            - Compliance and accreditation support

            ## Authentication
            The API uses JWT (JSON Web Tokens) for authentication. Include the JWT token in the Authorization header for all protected endpoints.

            ## Rate Limiting
            - Standard API calls: 100 requests per minute
            - Bulk operations: 20 requests per minute

            ## Data Security
            All educational data is encrypted in transit and at rest, ensuring compliance with educational privacy standards and the highest level of security for student and institutional information.
            """,
            'termsOfService': 'https://kisiwa-tech.ac.ke/terms/',
            'contact': {
                'name': 'KISNAP Support',
                'url': 'https://kisiwa-tech.ac.ke/support',
                'email': 'support@kisiwa-tech.ac.ke'
            },
            'license': {
                'name': 'Proprietary',
                'url': 'https://kisiwa-tech.ac.ke/license'
            },
            'x-logo': {
                'url': 'https://kisiwa-tech.ac.ke/logo.png'
            }
        },
        'components': {
            'securitySchemes': {
                'bearerAuth': {
                    'type': 'http',
                    'scheme': 'bearer',
                    'bearerFormat': 'JWT'
                }
            }
        },
    }

    # API Documentation UI Settings
    API_DOC_UI = 'redoc'
    ELEMENTS_CONFIG = {
        'theme': 'light',
        'hideTryIt': False,
        'hideExport': False,
        'hideSourceCode': True
    }

    # General Configuration
    ENVIRONMENT = 'development'
    DEBUG = True
    TESTING = True

    # Security Settings
    SECRET_KEY = "os.environ.get('SECRET_KEY')"
    JWT_SECRET_KEY = os.environ.get('JWT_SECRET_KEY')
    JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(hours=1)
    JWT_REFRESH_TOKEN_EXPIRES = datetime.timedelta(days=30)
    APP_NAME = "KISNAP"
    FRONTEND_URL="https://lms.mutabletech.co.ke"
    FONT_PATH='./static/fonts/'

    # Database Configuration
    DATABASE_NAME = os.environ.get('DATABASE_NAME', 'kisiwa_tech_db')
    DATABASE_PASSWORD = os.environ.get('DATABASE_PASSWORD')
    DATABASE_USER = os.environ.get('DATABASE_USER')
    DATABASE_HOST = os.environ.get('DATABASE_HOST', 'localhost')
    DATABASE_PORT = os.environ.get('DATABASE_PORT', '5432')
    DATABASE_AUTHOR = os.environ.get('DATABASE_AUTHOR', 'KISNAP')
    DATABASE_URL = os.environ.get('DATABASE_URL', 'sqlite:///test.db')

    # File Upload Settings
    UPLOAD_DIR = os.path.join(base, "/static/uploads/")
    STUDENT_DOCUMENTS_DIR = os.path.join(UPLOAD_DIR, "/static/uploads/students/")
    COURSE_MATERIALS_DIR = os.path.join(UPLOAD_DIR, "/static/uploads/courses/")
    TUTOR_DOCUMENTS_DIR = os.path.join(UPLOAD_DIR, "/static/uploads/tutors/")
    ACADEMIC_RECORDS_DIR = os.path.join(UPLOAD_DIR, "/static/uploads/records/")
    MAX_CONTENT_LENGTH = 500 * 1024 * 1024  # 500MB max file size (for video uploads)
    ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'pdf', 'docx', 'xlsx', 'txt', 'pptx', 'mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'}

    # Email Configuration
    MAIL_SERVER = os.environ.get('MAIL_SERVER', 'mail.mutabletech.co.ke')
    MAIL_PORT = int(os.environ.get('MAIL_PORT', 465))
    MAIL_USE_TLS = False
    MAIL_USE_SSL = True
    MAIL_USERNAME = os.environ.get('NO_REPLY_EMAIL')
    MAIL_PASSWORD = os.environ.get('NO_REPLY_PASSWORD', 'z}Y{WN$jV=Sv')
    NOREPLY_EMAIL = os.environ.get('NO_REPLY_EMAIL')
    NOREPLY_PASSWORD = os.environ.get('NO_REPLY_PASSWORD')
    MAIL_SENDER = os.environ.get('NO_REPLY_EMAIL', 'kisiwa@mutabletech.co.ke')
    SITE_URL = "https://localhost:5000"
    INSTITUTION_NAME = "KISNAP"
    
    # Admin Configuration
    ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL')
    ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD')
    
    # Academic Management Settings
    SEMESTER_DURATION_WEEKS = 16
    ACADEMIC_YEAR_START_MONTH = 1  # January
    ATTENDANCE_TRACKING_ENABLED = True
    GRADE_POINT_SCALE = 4.0  # GPA scale
    MINIMUM_ATTENDANCE_PERCENTAGE = 75
    ASSIGNMENT_SUBMISSION_BUFFER_HOURS = 24
    DEFAULT_PAGINATION_LIMIT = 25
    
    # Notification Settings
    ENROLLMENT_NOTIFICATIONS = True
    GRADE_RELEASE_NOTIFICATIONS = True
    ATTENDANCE_ALERTS = True
    FEE_PAYMENT_REMINDERS = True
    TIMETABLE_CHANGE_NOTIFICATIONS = True
    
    # SMS Configuration (AfricasTalking)
    AFRICASTALKING_USERNAME = "KISIWA_TECH"
    AFRICASTALKING_API_KEY = os.environ.get('AT_API_KEY')
    
    # Integration Settings
    MAPS_API_KEY = os.environ.get('MAPS_API_KEY')
    PAYMENT_GATEWAY_API_KEY = os.environ.get('PAYMENT_GATEWAY_API_KEY')
    SMS_API_KEY = os.environ.get('SMS_API_KEY')
    STATIC_FOLDER = os.path.join(base, 'static')

class DevelopmentConfig(BaseConfig):
    """Development configuration."""
    DEBUG = True
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    API_URL = "http://localhost:5000/"
    # Enable more detailed logging for development
    LOG_LEVEL = "DEBUG"
    # Enable demo mode with sample data
    DEMO_MODE = True
    # Faster token expiry for testing
    JWT_ACCESS_TOKEN_EXPIRES = datetime.timedelta(minutes=30)

class TestingConfig(BaseConfig):
    """Testing configuration."""
    TESTING = True
    DEBUG = True
    # Use in-memory SQLite for tests
    SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"
    # Disable email sending during tests
    MAIL_SUPPRESS_SEND = True

class ProductionConfig(BaseConfig):
    """Production configuration."""
    DEBUG = False
    TESTING = False
    ENVIRONMENT = 'production'
    API_URL = "https://api.kisiwa-tech.ac.ke/"
    # Enhanced security for production
    SESSION_COOKIE_SECURE = True
    REMEMBER_COOKIE_SECURE = True
    JWT_COOKIE_SECURE = True
    # Restrict API documentation in production
    OPENAPI_SWAGGER_UI_PATH = None
    OPENAPI_REDOC_PATH = '/api/v1/documentation'
    # Lower debugging level for production
    LOG_LEVEL = "ERROR"
    # Production specific settings
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    DEMO_MODE = False
    # Enhanced rate limiting for production
    RATELIMIT_DEFAULT = "60/minute"
    RATELIMIT_STORAGE_URL = "redis://localhost:6379/0"