"""
Django settings for Datamplify project.

Generated by 'django-admin startproject' using Django 5.2.4.

For more information on this file, see
https://docs.djangoproject.com/en/5.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.2/ref/settings/
"""

from pathlib import Path
import os,logging

from decouple import Config, RepositoryEnv

# Path to your .env
ENV_FILE = "/var/www/Datamplify/.env"

if os.path.exists(ENV_FILE):
    config = Config(RepositoryEnv(ENV_FILE))  # ✅ now 'config' exists
else:
    from decouple import config  # fallback to system env vars

# Always load from absolute path


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


logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# logger = logging.getLogger("custom_logger")



# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent



ENV_FILE = os.path.join(BASE_DIR, ".env")

LOGIN_URL = config('LOGIN_URL')
LOGIN_REDIRECT_URL = '/'

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!

# ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(',')




# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #Oauth
    'oauth2_provider',
    'rest_framework',

    #Apps
    'authentication',
    'Connections',
    'FlowBoard',
    'TaskPlan',
    'Monitor',
    'Tasks_Scheduler',

    #swagger
    'drf_yasg', 

    "corsheaders",

    'debug_toolbar',



]
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

# Methods allowed for CORS
CORS_ALLOW_METHODS = [
    'DELETE',
    'OPTIONS',
    'PATCH',
    'GET',
    'POST',
    'PUT',
]

# Non-standard headers allowed in the request
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]


# CSRF_TRUSTED_ORIGINS = [config('CSRF_TRUSTED_ORIGINS')]
# CORS_ALLOWED_ORIGINS = config("CORS_ALLOWED_ORIGINS",cast=lambda v: [s.strip() for s in v.split(",")])

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',

    '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',
    # 'oauth2_provider.middleware.OAuth2TokenMiddleware',


]

ROOT_URLCONF = 'Datamplify.urls'

ALLOWED_HOSTS = [
    '*'
]


# ALLOWED_HOSTS = [
#     host.strip()
#     for host in config("ALLOWED_HOSTS", "").split(",")
#     if host.strip()
# ]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "authentication/templates")],
        '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 = 'Datamplify.wsgi.application'
OAUTH2_PROVIDER = {
    "SCOPES": {
        "read": "Read access to Datamplify resources",
        "write": "Write access to Datamplify resources",
    }
}




# Database
# https://docs.djangoproject.com/en/5.2/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }


# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': config('DEV_DB_NAME'),
#         'USER': config('DB_USER'),
#         'PASSWORD': config('DB_PASSWORD'),
#         'HOST': config('DB_HOST'),
#         'PORT': config('DB_PORT'),
#     },
#     'QA': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': config('QA_DB_NAME'),
#         'USER': config('DB_USER'),
#         'PASSWORD': config('DB_PASSWORD'),
#         'HOST': config('DB_HOST'),
#         'PORT': config('DB_PORT'),
#     },
#     'Demo': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': config('DEMO_DB_NAME'),
#         'USER': config('DB_USER'),
#         'PASSWORD': config('DB_PASSWORD'),
#         'HOST': config('DB_HOST'),
#         'PORT': config('DB_PORT'),
#     },
#     'local': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT'),
    }
    
}


Integration_Credentials = {
    "QUICKBOOKS": {
        "CLIENT_ID": config("QUICKBOOKS_CLIENT_ID"),
        "CLIENT_SECRET": config("QUICKBOOKS_CLIENT_SECRET"),
        "REDIRECT_URI":config("QUICHBOOKS_REDIRECT_URI")
    },
    "SALESFORCE": {
        "CLIENT_ID": config("SALESFORCE_CLIENT_ID"),
        "CLIENT_SECRET": config("SALESFORCE_CLIENT_SECRET"),
        "REDIRECT_URI":config("SALESFORCE_REDIRECT_URI")
    },
    # "CONNECTWISE": {
    #     "CLIENT_ID": config("CONNECTWISE_CLIENT_ID"),
    #     "CLIENT_SECRET": config("CONNECTWISE_CLIENT_SECRET"),
    # },
    # "DBT": {
    #     "CLIENT_ID": config("DBT_CLIENT_ID"),
    #     "CLIENT_SECRET": config("DBT_CLIENT_SECRET"),
    # },
    "HALOPSA": {
        "CLIENT_ID": config("HALOPSA_CLIENT_ID"),
        "CLIENT_SECRET": config("HALOPSA_CLIENT_SECRET"),
        "REDIRECT_URI":config("HALOPSA_REDIRECT_URI")
    },
    "PAX8": {
        "CLIENT_ID": config("PAX8_CLIENT_ID"),
        "CLIENT_SECRET": config("PAX8_CLIENT_SECRET"),
    },
    # "BAMBOOHR": {
    #     "CLIENT_ID": config("BAMBOOHR_CLIENT_ID"),
    #     "CLIENT_SECRET": config("BAMBOOHR_CLIENT_SECRET"),
    # },
    "JIRA": {
        "CLIENT_ID": config("JIRA_CLIENT_ID"),
        "CLIENT_SECRET": config("JIRA_CLIENT_SECRET"),
        "REDIRECT_URI":config("JIRA_REDIRECT_URI")
    },
    # "SHOPIFY": {
    #     "CLIENT_ID": config("SHOPIFY_CLIENT_ID"),
    #     "CLIENT_SECRET": config("SHOPIFY_CLIENT_SECRET"),
    # },
    # "TALLY": {
    #     "CLIENT_ID": config("TALLY_CLIENT_ID"),
    #     "CLIENT_SECRET": config("TALLY_CLIENT_SECRET"),
    # },
    "GOOGLESHEETS": {
        "CLIENT_ID": config("GOOGLESHEET_CLIENT_ID"),
        "CLIENT_SECRET": config("GOOGLESHEET_CLIENT_SECRET"),
    },
    "NINJA": {
        "CLIENT_ID": config("NINJA_CLIENT_ID"),
        "CLIENT_SECRET": config("NINJA_CLIENT_SECRET"),
    },
    "GOOGLEANALYTICS": {
        "CLIENT_ID": config("GOOGLEANALYTICS_CLIENT_ID"),
        "CLIENT_SECRET": config("GOOGLEANALYTICS_CLIENT_SECRET"),
    },
    "HUBSPOT": {
        "CLIENT_ID": config("HUBSPOT_CLIENT_ID"),
        "CLIENT_SECRET": config("HUBSPOT_CLIENT_SECRET"),
    },
    "IMMYBOT": {
        "CLIENT_ID": config("IMMYBOT_CLIENT_ID"),
        "CLIENT_SECRET": config("IMMYBOT_CLIENT_SECRET"),
    },
    "ZOHO": {
        "CLIENT_ID": config("ZOHO_CLIENT_ID"),
        "CLIENT_SECRET": config("ZOHO_CLIENT_SECRET"),
        "REDIRECT_URI":config("ZOHO_REDIRECT_URI")
    },
    

}


CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/1",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}


#oauth2

AUTH_USER_MODEL = 'authentication.UserProfile'



CLIENT_ID = config("OAUTH_CLIENT_ID")

CLIENT_SECRET = config("OAUTH_CLIENT_SECRET")

Fernet_Key = config('DB_Fernet_Key').encode()

REST_FRAMEWORK = {
    "EXCEPTION_HANDLER": "integration_injection.custom_exception_handler"
}


# REST_FRAMEWORK = {
#     'DEFAULT_AUTHENTICATION_CLASSES': (
#         'oauth2_provider.contrib.rest_framework.OAuth2Authentication',  
        
#     ),
#     'DEFAULT_PERMISSION_CLASSES': (
#         'rest_framework.permissions.IsAuthenticated',
#     ),

# }
AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'oauth2_provider.backends.OAuth2Backend',
)

OAUTH2_PROVIDER = {
    "ACCESS_TOKEN_EXPIRE_SECONDS": 57600,  # 1 hour
    "REFRESH_TOKEN_EXPIRE_SECONDS": 2592000,  # 30 days
    'ROTATE_REFRESH_TOKEN': True,
}

# Password validation
# https://docs.djangoproject.com/en/5.2/ref/settings/#auth-password-validators

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
# https://docs.djangoproject.com/en/5.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.2/howto/static-files/

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')  # Or use an absolute path like '/var/www/Datamplify/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Mail

Link_url = config('LINK_URL')
TOKEN_URL = config('TOKEN_URL')
REDIRECT_URI = config('REDIRECT_URI')
airflow_host = config('AIRFLOW_HOST')
airflow_url = config('AIRFLOW_URL')
airflow_username = config('AIRFLOW_USER')
airflow_password = config('AIRFLOW_PASSWORD')
config_dir = config('CONFIGS_DIR')

# if DATABASES['default']['NAME'] =='Datamplify_DEV':

    # Link_url = 'http://202.65.155.119/'
    # TOKEN_URL = 'http://138.252.68.41/v1/authentication/oauth2/token/'
    # REDIRECT_URI = 'http://138.252.68.41/v1/nocallback/'
    # airflow_host = "http://138.252.68.41:8080"
    # airflow_url = "http://138.252.68.41:8080/auth/token"
    # airflow_username = "admin"
    # airflow_password = "TUff7tv8g6RVRp97"
    # config_dir = '/var/www/Configs'

    # Link_url = 'http://localhost:4201/'
    # TOKEN_URL = 'http://127.0.0.1:8000/v1/authentication/o/token/'
    # REDIRECT_URI = 'http://127.0.0.1:8000/v1/nocallback/'
    # airflow_host = "http://127.0.0.1:8080"
    # airflow_url = "http://127.0.0.1:8080/auth/token"
    # airflow_username = "airflow"
    # airflow_password = "airflow"
    
# else:
    # Link_url = 'http://localhost:4201/'
    # TOKEN_URL = 'http://127.0.0.1:8000/v1/authentication/oauth2/token/'
    # REDIRECT_URI = 'http://127.0.0.1:8000/v1/nocallback/'
    # airflow_host = "http://127.0.0.1:8080"
    # airflow_url = "http://127.0.0.1:8080/auth/token"
    # airflow_username = "airflow"
    # airflow_password = "airflow"
    # config_dir = os.path.join(BASE_DIR,'configs')




EMAIL_BACKEND = config('EMAIL_BACKEND')
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool)
EMAIL_PORT = config('EMAIL_PORT', cast=int)
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')

AWS_S3_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID')
AWS_S3_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME')


file_save_path= 's3'

CREDENTIAL_ENCRYPTION_KEY = config('ENCRYPTION_KEY')

clickhouse_host = config('CLICKHOUSE_HOST')
clickhouse_port = config('CLICKHOUSE_PORT')
clickhouse_username = config('CLICKHOUSE_USERNAME')
clickhouse_password = config('CLICKHOUSE_PASSWORD')
clickhouse_database = config('CLICKHOUSE_DATABASE')

#Ninja
if config('ENVIRONMENT')=='DEVELOPMENT':
    DEBUG = True
    SILKY_PYTHON_PROFILER = True

    DEBUG_TOOLBAR_CONFIG = {
        "SHOW_TOOLBAR_CALLBACK": lambda request: True,
    }
    INTERNAL_IPS = ['localhost']