"""
Django settings for po_service project.

Generated by 'django-admin startproject' using Django 4.2.16.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
from pathlib import Path
from dotenv import load_dotenv

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-*lzrjk7zfv!hhe14o&*hsh4h)k)2@wt=dr@!k)xd7%4ke588oj'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'django_extensions',

    'po_app',
    'declarations'
]

MIDDLEWARE = [
    'django.middleware.gzip.GZipMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'po_app.middlewares.SecureHeaderMiddleware',
]
CORS_ALLOW_CREDENTIALS = True

# The origin of your frontend application
CORS_ALLOWED_ORIGINS = [
    'http://localhost:5173',
    'http://10.0.2.8:8081',
    'http://10.0.2.8:8082',
    'http://94.136.187.179:8082'
]

CORS_ALLOW_HEADERS = [
    "content-type",
    "authorization",
    "x-requested-with",
    "x-auth-token",
    "accept",
    "origin",
    "user-agent",
    "x-api-key",
    "x-content-type"
]

ROOT_URLCONF = 'po_service.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # custom global 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 = 'po_service.wsgi.application'


# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'
# TIME_ZONE= 'Asia/Kolkata'

USE_I18N = True

USE_TZ = False

ENV_PATH = Path(__file__).resolve().parent.parent.parent.parent

env_file = ENV_PATH / f".env"

if env_file.exists():
    load_dotenv(env_file)
else:
    print(f"⚠️ Env file not found: {env_file}")


environment = os.environ.get('ENVIRONMENT')


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# Function to read environment variables from a file
def load_env(file_path):
    with open(file_path) as f:
        for line in f:
            # Ignore empty lines and comments
            if line.strip() and not line.startswith('#'):
                key, value = line.strip().split('=', 1)
                os.environ[key] = value

if environment == 'prod':
    # Load production environment
    load_env(r'C:\Apache24\htdocs\OrderPro_ERP\.env.prod')
elif environment == 'staging':
    # Load staging/UAT environment
    load_env(r'C:\Apache24\htdocs\OrderPro_ERP\.env.staging')  
else:
    # Load development environment
    load_env(r"D:\diffrenz\order_pro\.env.dev")  

# # Now you can access the environment variables like this
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
DEBUG = os.environ.get('DEBUG')

DATABASES = {
    'default': {
        'ENGINE': 'mssql',
        'NAME': os.environ.get('DATABASE_NAME'),
        'HOST':  os.environ.get('HOSTNAME'),
        'USER': os.environ.get('DATABASE_USER'), 
        'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 
        'PORT': '',  # Leave blank to use default SQL Server port (1433)
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',  # Ensure this driver is installed
            'trusted_connection': 'yes',
        },
    },
   
    'secondary': {
        'ENGINE': 'mssql',
        'NAME': os.environ.get('SECONDARY_DATABASE'),
        'HOST': os.environ.get('SECONDARY_DATABASE_HOST'),  # Replace with your server instance (e.g., localhost\SQLEXPRESS)
        'USER': os.environ.get('SECONDARY_DATABASE_USER'),
        'PASSWORD': os.environ.get('SECONDARY_DATABASE_PASSWORD'),
        'PORT': '',  # Default port for SQL Server; leave empty if default
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',  # Ensure this matches your installed ODBC driver
            'trusted_connection': 'yes',
        },
        }
}

PRODUCT_API_URL = os.environ.get('PRODUCT_API_URL')
CUSTOMER_API_URL = os.environ.get('CUSTOMER_API_URL')
DELIVERY_API_URL = os.environ.get('DELIVERY_API_URL')
USER_API_URL = os.environ.get('USER_API_URL')
PO_API_URL = os.environ.get('PO_API_URL')
API_KEY = os.environ.get('API_KEY')

MEDIA_ROOT = os.path.join(BASE_DIR, "order_documents")
MEDIA_URL = os.environ.get('MEDIA_URL')
# DOCUMENTS_ROOT=os.environ.get('FILE_ROOT')
# MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# QUOTATION_FILE_PATH='http://94.136.187.179/PVSGent/purchase_order_service/quotation_files/'
QUOTATION_FILE_PATH=os.environ.get('QUOTATION_FILE_PATH')

EMAIL_BACKEND =  os.environ.get('EMAIL_BACKEND')
EMAIL_HOST =  os.environ.get('EMAIL_HOST')
EMAIL_PORT =  os.environ.get('EMAIL_PORT')

EMAIL_USE_TLS =  True
EMAIL_USE_SSL =  False

EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
ORDER_REQUEST_FILE_BASE_URL = os.environ.get('ORDER_REQUEST_FILE_BASE_URL')
IMAGE_FILE_PATH = os.environ.get('IMAGE_FILE_PATH')

LOG_PLAN_PATH = os.environ.get('LOG_PLAN_PATH')

ERP_BASE_URL = os.environ.get('ERP_BASE_URL')
ERP_AUTH_URL = os.environ.get('ERP_AUTH_URL')
ERP_CLIENT_ID = os.environ.get('ERP_CLIENT_ID')
ERP_CLIENT_SECRET = os.environ.get('ERP_CLIENT_SECRET')
ERP_GRANT_TYPE = os.environ.get('ERP_GRANT_TYPE')
ERP_USERNAME = os.environ.get('ERP_USERNAME')
ERP_PASSWORD = os.environ.get('ERP_PASSWORD')


CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "erp-cache"
    }
}


