"""
Django settings for djapi project.

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

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/
"""

import os
from pathlib import Path

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

# 从 .env_loader 加载环境变量检测（本地开发可用 shell export 或 .env 文件）
from .env_loader import get_env, get_env_bool

# 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 = get_env('DJANGO_SECRET_KEY', required=not get_env_bool('DJANGO_DEBUG', True))

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = get_env_bool('DJANGO_DEBUG', True)

ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'uwsgi','api.doorcome.cn','doorcome.cn','echart.doorcome.cn']

CSRF_TRUSTED_ORIGINS = [
    'https://api.doorcome.cn',
    'https://echart.doorcome.cn',
]

#以下跨域名访问配置
CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOWED_ORIGINS = [
    "https://api.doorcome.cn",
    "https://echart.doorcome.cn",
]
#允许的 HTTP 方法和头部：
CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]
CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
    'X-CSRFToken',
]
CORS_ALLOW_CREDENTIALS = True #允许携带凭据：
# 新增配置
CORS_EXPOSE_HEADERS = ['Content-Type', 'X-CSRFToken']
SESSION_COOKIE_DOMAIN = ".doorcome.cn"  # 改为顶级域名共享cookie
CSRF_COOKIE_DOMAIN = ".doorcome.cn"
#SESSION_COOKIE_SAMESITE = 'Lax' #Lax模式会阻止跨域AJAX请求发送cookies
SESSION_COOKIE_SAMESITE = 'None'  # 必须为None才能跨域传cookie
CSRF_COOKIE_SAMESITE = 'None'     # 同步修改CSRF的SameSite
#以上跨域名访问配置
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
CSRF_COOKIE_SECURE = True  # 如果使用 HTTPS 则设为 True
CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_SECURE = True  # 如果使用 HTTPS 则设为 True
#SESSION_COOKIE_DOMAIN = "api.doorcome.cn"  # 可选，根据实际需求
# 允许所有域名进行跨域访问
CORS_ALLOW_ALL_ORIGINS = True

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders', #跨域名访问 2025-07-08
    'api', # my 1st application created 2025/5/23
    'rest_framework',
    'drf_spectacular',  # 新增：drf-spectacular
]

# 配置 DRF 默认 schema 生成器
REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

# 配置 spectacular
SPECTACULAR_SETTINGS = {
    'TITLE': 'Finance API',
    'DESCRIPTION': 'A 股金融数据 API — 行情、财务、分红、指数、融资融券、新闻联播',
    'VERSION': '1.0.0',
    'SERVE_INCLUDE_SCHEMA': False,
    'TAGS': [
        {'name': '行情', 'description': '个股日线行情、技术参数'},
        {'name': '基础数据', 'description': '股票基本信息、行业分类'},
        {'name': '财务', 'description': 'EPS、财务报表分析'},
        {'name': '分红', 'description': '股息率、TTM 分红'},
        {'name': '指数', 'description': '指数行情与查询'},
        {'name': '融资融券', 'description': '融资融券明细与汇总'},
        {'name': '新闻联播', 'description': '新闻联播 ASR 转写与 AI 精编'},
        {'name': '日报', 'description': 'AI 财经日报查询（news_report / news_event）'},
        {'name': '系统', 'description': '系统信息'},
    ],
}

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'corsheaders.middleware.CorsMiddleware', #跨域名访问  2025-07-08
    '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 = 'djapi.urls'

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


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

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


# 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'
LANGUAGE_CODE = 'zh-hans' #简体中文，影响管理界面？

#TIME_ZONE = 'UTC'
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = '/static/'
# 此时访问django的admin管理后台时，静态资源会调取失败。这时可以将该项目所有静态资源统一收集到一个文件夹下，然后由nginx统一去调取，真正做到动静分离(动的给uWSGI，静的由nginx直接调取)：
STATIC_ROOT = BASE_DIR / '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'

CORS_DEBUG = True  # 显示详细 CORS 错误
LOGGING = {
    'version': 1,
    'handlers': {
        'console': {'class': 'logging.StreamHandler'},
    },
    'loggers': {
        'corsheaders': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },
}
