import os
from pathlib import Path
from dotenv import load_dotenv  # Import dotenv

# Load environment variables from .env file
load_dotenv()

def str_to_bool(value):
    return value.lower() in ("true", "1", "yes")


# Base directory of the project
BASE_DIR = Path(__file__).resolve().parent.parent

# SECURITY WARNING: Keep the secret key used in production secret!
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'fallback-secret-key')

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


# Allowed Hosts
ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    'jazzmin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'setting',
    'subscribe',
    'razorpay',
    'django_extensions',
    'users',
    'wallet',
    'skyplay_api',
    'rest_framework',
    'drf_yasg',
    'testapp',
    'watcho',
    'import_export',
    #'channels',
    'django.contrib.sites',  # For allauth
    'allauth',
    #'allauth.account',
    #'allauth.socialaccount',
    'ott_subscription',  # Your app
    'corsheaders',
    'lockbox',
    'iptv_activation',
    'maintenance_mode',
    'pricing_plan',
    'email_template',
    'feedback',
    'colorfield',
    'ckeditor',



]
SITE_ID = 1

# Allow all origins for development purposes
CORS_ALLOW_ALL_ORIGINS = True

AUTH_USER_MODEL = "users.User"
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',  # Default
)
# Twilio settings (for phone number OTP)
TWILIO_ACCOUNT_SID = 'your_account_sid'
TWILIO_AUTH_TOKEN = 'your_auth_token'
TWILIO_PHONE_NUMBER = 'your_twilio_phone_number'

# Email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'developer@skylink.net.in'
EMAIL_HOST_PASSWORD = 'vrghuycfaljvjobi'
# Optional settings (you can leave them out if not needed)
DEFAULT_FROM_EMAIL = 'developer@skylink.net.in'  # Default from email (optional)
EMAIL_SUBJECT_PREFIX = '[SKYLINK] '  # Optional prefix for email subject lines


ZEPTOMAIL_API_URL = "https://api.zeptomail.in/v1.1/email"
ZEPTOMAIL_API_KEY = "PHtE6r0NRe3oj2Z6oRYH5/SwR5OsM4h7/O82JFFG5ohFDqRWHk0Dq40tkzPmo0sjAPlEEaLOy9pssejKseKBIme4N2saWmqyqK3sx/VYSPOZsbq6x00YuFUSdkffUILuc9Vi3CTUud3aNA=="
ZEPTOMAIL_FROM_EMAIL = "info@skylink.net.in"



AUTH_USER_MODEL = "users.User"

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',  # Ensure this is kept if you want auth
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'allauth.account.middleware.AccountMiddleware',
    'maintenance_mode.middleware.MaintenanceModeMiddleware',
]



MAINTENANCE_MODE = False

MAINTENANCE_MODE_IGNORE_URLS = (
    r'^/admin/',  # Allow access to /admin
)

MAINTENANCE_MODE_IGNORE_IP_ADDRESSES = (
'103.130.90.103',  # Allow local access
)

MAINTENANCE_MODE_IGNORE_SUPERUSER = True

CSRF_COOKIE_HTTPONLY = True  # This makes the CSRF cookie inaccessible to JavaScript.
CSRF_COOKIE_SECURE = False  # Set to True if you're using HTTP

ROOT_URLCONF = 'skyplay_api_hub.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 = 'skyplay_api_hub.wsgi.application'

# Database Configuration
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('DJANGO_DATABASE_NAME', 'skyplay_api_hub'),
        'USER': os.getenv('DJANGO_DATABASE_USER', 'root'),
        'PASSWORD': os.getenv('DJANGO_DATABASE_PASSWORD', 'Skyplay123@hub'),
        'HOST': os.getenv('DJANGO_DATABASE_HOST', '103.99.150.55'),
        'PORT': os.getenv('DJANGO_DATABASE_PORT', '3306'),
    }
}

# Password validation
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
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# ✅ Fixed Static Files Configuration
STATIC_URL = '/static/'
STATIC_ROOT = '/var/www/skyplay_api_hub/static/'
STATICFILES_DIRS = []  # Ensure this is empty to avoid conflicts

# Media Files Configuration
MEDIA_URL = '/media/'
MEDIA_ROOT = '/var/www/skyplay_api_hub/media'
MAX_UPLOAD_SIZE = 5 * 1024 * 1024  # 5 MB

# Default primary key field type
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Razorpay API Keys

RAZORPAY_KEY_ID = os.getenv('RAZORPAY_KEY_ID')
RAZORPAY_KEY_SECRET = os.getenv('RAZORPAY_SECRET')


# Logging Configuration
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,

    "formatters": {
        "simple": {
            "format": "[{asctime}] {levelname} {name}: {message}",
            "style": "{",
        },
    },

    "handlers": {
        "error_file": {
            "level": "ERROR",
            "class": "logging.FileHandler",
            "filename": "/var/www/skyplay_api_hub/logs/django_error.log",
            "formatter": "simple",
        },
    },

    "loggers": {
        "django": {
            "handlers": ["error_file"],
            "level": "ERROR",
            "propagate": False,
        },
    },

    "root": {
        "handlers": ["error_file"],
        "level": "ERROR",
    },
}




# Swagger Settings (for API Docs)
SWAGGER_SETTINGS = {
    'LOGIN_REQUIRED': False,
    'USE_SESSION_AUTH': False,
}

# Security Settings (for Production)
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True

# Login URL (Optional - Remove if you don't want login restriction)
LOGIN_URL = '/login/'  # Only add this if you want to enforce login globally

# Disable login for the subscribe page
# If you don't want to enforce login, remove the `LOGIN_URL` or override `@login_required`

ENCRYPTION_PASS_PHRASE = "1234"


##Session 
SESSION_COOKIE_AGE = 1800  # 30 minutes (in seconds)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # If you want the session to expire when the user closes the browser, set:
SESSION_SAVE_EVERY_REQUEST = True #SESSION_SAVE_EVERY_REQUEST = True

## Ott Play
OTTPLAY_API_URL = 'https://bundlr.ottplay.com/api/v4.0/subscriber/action'
OTTPLAY_AUTH_TOKEN = '0dWjkyIGfDGbtIplnXvyE8sdOPy7B7FQjRbt52QBRrYG0lM7CZbcLHbotQzvEo5Glw24x39Dxsu8JJ0IR8gOrmIVdBiM5a5qNVYJlXNijXQpGrb63LfmAodGYlgQadMOX4Q1OGXvd5j1jrqHOFDikvJtmjPNoL8tvkihvw6njG4NNUpFdYhEQrmg0QzvrESHxBIQutxKLaQk1VP3nnHDx7wMXxtypyLX6WZEQFotjJsk7stmCAP0HxowsUKsQlY',
OTTPLAY_LOGIN_ID = 'fortknox_isp'
OTTPLAY_OPER_CODE = '18403'


## Playbox

PLAYBOX_API_URL = "https://8fjpx02rmk.execute-api.ap-south-1.amazonaws.com/prod/v3/assignPack"
PLAYBOX_API_KEY = "spfFnjetet705D8sngf7H7kojE04oYkn7DNECvDv"
#PLAYBOX_PARTNET_KEY = "8588f445e9a912e828597d43702aa89aaceacbe149db175366ca95bab1e31ebb85e191e7484116fc2de11b9d9247b5f03786ed689c53716a5a0cdc4280019887"
PLAYBOX_PARTNET_KEY = "a69e4a8128674878b4c1713f84b5b7d7e8d5e1a5f9d25b887999886ba0d4a596532c8b1495229c1835b76d73a438df5ce9c48ec8aaa38bfb1a07d3bbf3f82ed1"


## Watcho 
WATCHO_API_URL =  "https://publicapis.dishtv.in/api/WatchoOne/SubscriptionRequestWatchoplan"
WATCHO_API_USER_NAME = "208"
WATCHO_API_PASSWORD = "sk$L!nk@2025"

## Zoho
API_BASE_URL = "https://fiber.net.in/api/v1"
API_AUTH_USERNAME = "fiber"
API_AUTH_PASSWORD = "1f06c10fafe0c8d92912e25513c29efc1d861363"



# Cashfree Payment Gateway
#CASHFREE_APP_ID = "TEST1096221338e898f7e92b7e32fb0e31226901"
#CASHFREE_SECRET_KEY = "cfsk_ma_test_e286de146f028777373338b71ff672b4_67ed03a3"
#CASHFREE_ENV = "SANDBOX"  # Change to "PROD"
#CASHFREE_API_VERSION = "2025-01-01"




# Cashfree Payment Gateway
CASHFREE_APP_ID = "118428905d91e21ba7de4afd1ba9824811"
CASHFREE_SECRET_KEY = "cfsk_ma_prod_c1881c753f7c7577d635d147da7b54ed_03e3956c"
CASHFREE_ENV = "PROD"  # Change to "PROD"
CASHFREE_API_VERSION = "2025-01-01"



## Zoho
NORTH_API_BASE_URL = "https://del.skyplay.app/api/v1"
NORTH_API_AUTH_USERNAME = "skylink"
NORTH_API_AUTH_PASSWORD = "9c567ac5456358c092f17252efb02289312576f7"

SMS_SEND_FLAG = 1
MAIL_SEND_FLAG = 1


#IPTV setup 
IPTV_BASE_URL = "http://api2.skyplay.in"
IPTV_TOKEN = "84a0103ea1780372cbc410e49114633e"
IPTV_LIMIT = 1
IPTV_PROXY_SERVER_ID = 194
TARIFF_ID = 152



CKEDITOR_5_CONFIGS = {
    'default': {
        'toolbar': [
            ['heading', '|', 'bold', 'italic', 'link'],
            ['bulletedList', 'numberedList', 'blockQuote'],
            ['undo', 'redo'],
            ['imageUpload'],
        ],
        'heading': {
            'options': [
                {'model': 'paragraph', 'title': 'Paragraph', 'class': 'ck-heading_paragraph'},
                {'model': 'heading1', 'view': 'h1', 'title': 'Heading 1', 'class': 'ck-heading_heading1'},
                {'model': 'heading2', 'view': 'h2', 'title': 'Heading 2', 'class': 'ck-heading_heading2'},
            ]
        },
        'image': {
            'toolbar': [
                'imageTextAlternative', '|', 'imageStyle:full', 'imageStyle:alignLeft', 'imageStyle:alignRight'
            ],
            'styles': [
                'full', 'alignLeft', 'alignRight'
            ]
        },
        'language': 'en',
    }
}

PING_CMD = "/usr/bin/ping"



JAZZMIN_SETTINGS = {
    "site_title": "SkyPlay Admin",
    "site_header": "SkyPlay Administration",
    "site_brand": "SkyPlay",

    "welcome_sign": "Welcome to SkyPlay Admin Panel",
    
    "search_model": [
        "auth.User",
        "ott_subscription.CashfreePayment",
    ],

    "topmenu_links": [
        {"name": "Dashboard", "url": "admin:index", "permissions": ["auth.view_user"]},
        {"name": "Website", "url": "/ott_subscription/login/", "new_window": True},
    ],

    "icons": {
        "auth": "fas fa-users",
        "auth.user": "fas fa-user",
        "auth.group": "fas fa-users-cog",

        "ott_subscription": "fas fa-tv",
        "ott_subscription.cashfreepayment": "fas fa-credit-card",

        "setting": "fas fa-cogs",
        "setting.paymentgatewaysettings": "fas fa-wallet",
    },

    "show_sidebar": True,
    "navigation_expanded": False,
    
      # Default Django
        "auth": "fas fa-user-shield",
        "auth.user": "fas fa-user",
        "auth.group": "fas fa-users-cog",
        "sites": "fas fa-globe",

        # Your Apps
        "channel_subscription": "fas fa-tv",
        "email_templates": "fas fa-envelope-open-text",
        "iptv_activation": "fas fa-broadcast-tower",
        "lockbox": "fas fa-lock",
        "ott_subscription": "fas fa-film",
        "pricing_plan": "fas fa-tags",
        "setting": "fas fa-cogs",
        "skyplay_api": "fas fa-plug",
        "users": "fas fa-users",
        "wallet": "fas fa-wallet",
        "widgets": "fas fa-puzzle-piece",
}


JAZZMIN_UI_TWEAKS = {
    # Sidebar behaviour
    "sidebar_disable_expand": False,   # ✅ allow toggle
    "sidebar_nav_small_text": False,
    "sidebar_text_size": "normal",

    # Keep sidebar icons visible
    "sidebar_fixed": True,
    "sidebar_collapsed": False,

    # Optional theme
    "theme": "flatly",
}

# Cashfree Payment Gateway
CASHFREE_APP_ID = "118428905d91e21ba7de4afd1ba9824811"
CASHFREE_SECRET_KEY = "cfsk_ma_prod_c1881c753f7c7577d635d147da7b54ed_03e3956c"
CASHFREE_ENV = "PROD"  # Change to "PROD"
CASHFREE_API_VERSION = "2025-01-01"

## Zoho
# NORTH_API_BASE_URL = "https://del.skyplay.app/api/v1"
# NORTH_API_AUTH_USERNAME = "skylink"
# NORTH_API_AUTH_PASSWORD = "1b7a0e2ab6ff94f13334ce2d05a1a5b9b472e72c"
