from .base import *
import os
import sys
from urllib.parse import urlparse

DEBUG = os.getenv('DEBUG', 'false').lower() == 'true'

ALLOWED_HOSTS = [h.strip() for h in os.getenv('ALLOWED_HOSTS', '*').split(',') if h.strip()]

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
from corsheaders.defaults import default_headers
CORS_ALLOW_HEADERS = list(default_headers) + [
    'authorization',
    'x-csrftoken',
]

csrf_trusted = os.getenv('CSRF_TRUSTED_ORIGINS', '').split(',')
CSRF_TRUSTED_ORIGINS = [o.strip() for o in csrf_trusted if o.strip()] or [
    'https://goaling.us',
    'http://goaling.us',
    'https://www.goaling.us',
    'http://www.goaling.us',
    'https://api.goaling.us',
    'http://api.goaling.us',
    'https://goalign.us',
    'http://goalign.us',
    'https://api.goalign.us',
    'http://api.goalign.us',
    'https://goalign-20d21.web.app',
    'https://goalign-20d21.firebaseapp.com',
]

database_url = os.getenv('DATABASE_URL')
if database_url:
    url = urlparse(database_url)
    engine = 'django.db.backends.postgresql'
    if 'mysql' in url.scheme:
        engine = 'django.db.backends.mysql'
    DATABASES = {
        'default': {
            'ENGINE': engine,
            'NAME': url.path[1:],
            'USER': url.username,
            'PASSWORD': url.password,
            'HOST': url.hostname,
            'PORT': url.port or (3306 if 'mysql' in engine else 5432),
        }
    }
else:
    db_engine = os.getenv('DB_ENGINE', 'django.db.backends.postgresql')
    db_name = os.getenv('DB_NAME') or os.getenv('PGDATABASE') or os.getenv('MYSQL_DATABASE')
    
    if db_engine == 'django.db.backends.sqlite3' or not db_name:
        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': BASE_DIR / 'db.sqlite3',
            }
        }
    else:
        DATABASES = {
            'default': {
                'ENGINE': db_engine,
                'NAME': db_name,
                'USER': os.getenv('DB_USER') or os.getenv('PGUSER') or os.getenv('MYSQL_USER', ''),
                'PASSWORD': os.getenv('DB_PASSWORD') or os.getenv('PGPASSWORD') or os.getenv('MYSQL_PASSWORD', ''),
                'HOST': os.getenv('DB_HOST') or os.getenv('PGHOST') or 'localhost',
                'PORT': os.getenv('DB_PORT') or os.getenv('PGPORT') or ('3306' if 'mysql' in db_engine else '5432'),
            }
        }

ENABLE_MOCK_FINANCE = os.getenv('ENABLE_MOCK_FINANCE', 'false').lower() == 'true'

# Security Settings for cPanel & Reverse Proxies
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = os.getenv('SECURE_SSL_REDIRECT', 'false').lower() == 'true'
SESSION_COOKIE_SECURE = os.getenv('SESSION_COOKIE_SECURE', 'false').lower() == 'true'
CSRF_COOKIE_SECURE = os.getenv('CSRF_COOKIE_SECURE', 'false').lower() == 'true'
SECURE_CONTENT_TYPE_NOSNIFF = True
