"""
Django settings for config project.

Generated by 'django-adminMIDDLEWARE = MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # できるだけ上部に
    'django.middleware.common.CommonMiddleware',

    'django.middleware.security.SecurityMiddleware',
    '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',
]aders.middleware.CorsMiddleware',  # できるだけ上部に
    'django.middleware.common.CommonMiddleware',

    'django.middleware.security.SecurityMiddleware',
    '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',
    # 'rog.middleware.DetailedRequestLoggingMiddleware',  # 一時的に無効化
    # 'rog.middleware.APIResponseEnhancementMiddleware',  # 一時的に無効化
] using Django 3.2.9.

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

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

from pathlib import Path
import environ
import os
import dj_database_url
import warnings
import logging

# Suppress matplotlib and other library debug logs
os.environ['MPLBACKEND'] = 'Agg'
warnings.filterwarnings('ignore')

# Disable specific library debug logging
logging.getLogger('matplotlib').setLevel(logging.WARNING)
logging.getLogger('matplotlib.font_manager').setLevel(logging.WARNING)
logging.getLogger('PIL').setLevel(logging.WARNING)

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

env = environ.Env(DEBUG=(bool, False))
environ.Env.read_env(env_file=".env")


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

# SECURITY WARNING: keep the secret key used in production secret!
#SECRET_KEY = 'django-insecure-@!z!i#bheb)(o1-e2tss(i^dav-ql=cm4*+$unm^3=4)k_ttda'
SECRET_KEY = env("SECRET_KEY")

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

#ALLOWED_HOSTS = []
ALLOWED_HOSTS = env("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',
    'django.contrib.gis',
    'rest_framework',
    'rest_framework_gis',
    'knox',
    'leaflet',
    'leaflet_admin_list',
    'rog.apps.RogConfig',
    'corsheaders',  # added
    'django_filters'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # できるだけ上部に
    'django.middleware.common.CommonMiddleware',

    'django.middleware.security.SecurityMiddleware',
    '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',
    # 'rog.middleware.APIResponseEnhancementMiddleware',  # 一時的にコメントアウト
]

ROOT_URLCONF = 'config.urls'

CORS_ALLOW_ALL_ORIGINS = True  # 開発環境のみ
CORS_ALLOW_CREDENTIALS = True

CORS_ALLOWED_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS'
]
CORS_ALLOWED_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

# 本番環境では以下のように制限する
CORS_ALLOWED_ORIGINS = [
     "https://rogaining.sumasen.net",
     "http://rogaining.sumasen.net",
]

# CSRFの設定
CSRF_TRUSTED_ORIGINS = [
    "http://rogaining.sumasen.net",
    "https://rogaining.sumasen.net",
]



TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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 = 'config.wsgi.application'


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


DATABASES = {
    'default': dj_database_url.config(
        default=f'postgis://{env("POSTGRES_USER")}:{env("POSTGRES_PASS")}@{env("PG_HOST")}:{env("PG_PORT")}/{env("POSTGRES_DBNAME")}',
        conn_max_age=600,
        conn_health_checks=True,
    ),
    'mobserver': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': 'gifuroge',
        'USER': env("POSTGRES_USER"),
        'PASSWORD': env("POSTGRES_PASS"),
        'HOST': env("PG_HOST"),
        'PORT': env("PG_PORT"),
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.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/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Tokyo'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

#STATIC_URL = '/static2/'
#STATIC_ROOT = BASE_DIR / "static"
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
#MEDIA_ROOT = BASE_DIR / "media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

#STATICFILES_DIRS = (os.path.join(BASE_DIR, "static2"),os.path.join(BASE_DIR, "media"))


AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend' , 'rog.backend.EmailOrUsernameModelBackend', )

AUTH_USER_MODEL = 'rog.CustomUser'


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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LEAFLET_CONFIG = {
    'DEFAULT_CENTER': (35.41864442627996, 138.14094040951784),
    'DEFAULT_ZOOM': 6,
    'MIN_ZOOM': 3,
    'MAX_ZOOM': 19,
    'DEFAULT_PRECISION': 6,
    'SCALE':"both",
    'ATTRIBUTION_PREFIX':"ROGAINING API",
    'TILES': [('Satellite', 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {'attribution': '&copy; ESRI', 'maxZoom': 19}),
          ('Streets', 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {'attribution': '&copy; Contributors'})]
}

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',  # デフォルトは認証不要に変更
    ],
}


#FRONTEND_URL = 'https://rogaining.intranet.sumasen.net'    # フロントエンドのURLに適宜変更してください
FRONTEND_URL = 'https://rogaining.sumasen.net'    # フロントエンドのURLに適宜変更してください

# この設定により、メールは実際には送信されず、代わりにコンソールに出力されます。
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_HOST = 'smtp.outlook.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'rogaining@gifuai.net'
EMAIL_HOST_PASSWORD = 'ctcpy9823"x~'
DEFAULT_FROM_EMAIL = 'rogaining@gifuai.net'

APP_DOWNLOAD_LINK = 'https://apps.apple.com/jp/app/%E5%B2%90%E9%98%9C%E3%83%8A%E3%83%93/id6444221792'
ANDROID_DOWNLOAD_LINK = 'https://play.google.com/store/apps/details?id=com.dvox.gifunavi&hl=ja'

SERVICE_NAME = '岐阜ナビ(岐阜ロゲのアプリ)'

# settings.py
DEFAULT_CHARSET = 'utf-8'

#REST_FRAMEWORK = {
#    'DEFAULT_RENDERER_CLASSES': [
#        'rest_framework.renderers.JSONRenderer',
#    ],
#    'JSON_UNICODE_ESCAPE': False,
#}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        #'file': {
        #    'level': 'DEBUG',
        #    'class': 'logging.FileHandler',
        #    'filename': os.path.join(BASE_DIR, 'logs/debug.log'),
        #    'formatter': 'verbose',
        #},
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'root': {
        'handlers': ['console'],
        'level': 'INFO',
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'rog': {
            #'handlers': ['file','console'],
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        # Suppress verbose debug logs from various libraries
        'matplotlib': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'geos': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'env': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'pyplot': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'font_manager': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
        'environ': {
            'handlers': ['console'],
            'level': 'WARNING',
            'propagate': False,
        },
    },
}

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
]

BLACKLISTED_IPS = ['44.230.58.114']  # ブロックしたい IP アドレスをここにリストとして追加

# AWS S3 Settings
AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY", default="")
AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY", default="")
AWS_STORAGE_BUCKET_NAME = env("S3_BUCKET_NAME", default="")
AWS_S3_REGION_NAME = env("AWS_REGION", default="us-west-2")
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com"

# S3 URL Generation
def get_s3_url(file_path):
    """Generate S3 URL for given file path"""
    if AWS_STORAGE_BUCKET_NAME and file_path:
        return f"https://{AWS_S3_CUSTOM_DOMAIN}/{file_path}"
    return None

# Bulk Upload Settings
BULK_UPLOAD_MAX_FILES = 50  # 一度にアップロードできる最大ファイル数
BULK_UPLOAD_MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB per file
BULK_UPLOAD_ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.heic']
BULK_UPLOAD_UPLOAD_DIR = 'bulk_checkin_photos/'

