import os
from pathlib import Path
from urllib.parse import urlparse
from dotenv import load_dotenv
from infisical_sdk import InfisicalSDKClient
import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration

load_dotenv()


def env_first(names, default=None):
    for name in names:
        val = os.getenv(name)
        if val:
            return val
    return default


INFISICAL_API_URL = env_first(
    ["INFISICAL_API_URL", "PROJECT_INFISICAL_API_URL", "project.INFISICAL_API_URL"],
    "https://app.infisical.com",
).rstrip("/")
INFISICAL_TOKEN = env_first(
    ["INFISICAL_TOKEN", "PROJECT_INFISICAL_TOKEN", "project.INFISICAL_TOKEN"]
)
INFISICAL_PROJECT_ID = env_first(
    ["INFISICAL_PROJECT_ID", "PROJECT_INFISICAL_PROJECT_ID", "project.INFISICAL_PROJECT_ID"]
)
INFISICAL_ENV = env_first(
    ["INFISICAL_ENV", "PROJECT_INFISICAL_ENV", "project.INFISICAL_ENV"]
)

missing = [name for name, val in [
    ("INFISICAL_TOKEN", INFISICAL_TOKEN),
    ("INFISICAL_PROJECT_ID", INFISICAL_PROJECT_ID),
    ("INFISICAL_ENV", INFISICAL_ENV),
] if not val]
if missing:
    raise RuntimeError(f"Missing required Infisical env vars: {', '.join(missing)}")

client = InfisicalSDKClient(host=INFISICAL_API_URL, token=INFISICAL_TOKEN)

# Fetch secrets from Infisical and load into environment.
secrets_response = client.secrets.list_secrets(
    environment_slug=INFISICAL_ENV,
    secret_path="/",
    project_id=INFISICAL_PROJECT_ID,
    include_imports=True,
    expand_secret_references=True,
    view_secret_value=True,
    recursive=True,
)
for secret in secrets_response.secrets:
    os.environ[secret.secretKey] = secret.secretValue

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

SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'dev-secret-key-change-in-production')

DEBUG = os.getenv('DEBUG', 'False') == 'True'

# Sentry/GlitchTip configuration
SENTRY_DSN = os.getenv('SENTRY_DSN', '')
if SENTRY_DSN:
    sentry_sdk.init(
        dsn=SENTRY_DSN,
        integrations=[DjangoIntegration()],
        auto_session_tracking=False,
        traces_sample_rate=0.01,
        release=os.getenv('RELEASE_VERSION', '1.0.0'),
        environment=os.getenv('ENVIRONMENT', 'production'),
        send_default_pii=False,
        debug=DEBUG,
    )

ALLOWED_HOSTS = ['*']

CSRF_TRUSTED_ORIGINS = ['https://orders.optovia.ru']

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'graphene_django',
    'orders_app',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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',
]

ROOT_URLCONF = 'orders.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'orders.wsgi.application'

def build_db_config(db_url_env_names):
    """
    Build DB settings from the first available DB URL env var.
    """
    db_url = env_first(db_url_env_names)
    if not db_url:
        raise RuntimeError(f"Missing required DB URL env var: one of {', '.join(db_url_env_names)}")

    parsed = urlparse(db_url)
    if not parsed.scheme or not parsed.path:
        raise RuntimeError("Invalid DATABASE_URL format")

    return {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': (parsed.path or '').lstrip('/'),
        'USER': parsed.username or '',
        'PASSWORD': parsed.password or '',
        'HOST': parsed.hostname or '',
        'PORT': str(parsed.port) if parsed.port else '',
    }


DATABASES = {'default': build_db_config(['ORDERS_DATABASE_URL', 'DATABASE_URL'])}

# Internationalization
LANGUAGE_CODE = 'ru-ru'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True

# Static files
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

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

# CORS
CORS_ALLOW_ALL_ORIGINS = True

# GraphQL
GRAPHENE = {
    'SCHEMA': 'orders_app.schema.schema',
    'MIDDLEWARE': [
        'orders_app.graphql_middleware.TeamJWTMiddleware',
    ],
}

# Logto JWT settings
LOGTO_JWKS_URL = os.getenv('LOGTO_JWKS_URL', 'https://auth.optovia.ru/oidc/jwks')
LOGTO_ISSUER = os.getenv('LOGTO_ISSUER', 'https://auth.optovia.ru/oidc')
LOGTO_ORDERS_AUDIENCE = os.getenv('LOGTO_ORDERS_AUDIENCE', 'https://orders.optovia.ru')

# Odoo connection
ODOO_URL = os.getenv('ODOO_URL', 'http://odoo:8069')
