"""
Django settings for core project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/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


def _load_env_file(path: str) -> None:
    """Load KEY=VALUE lines into os.environ (does not override existing)."""
    try:
        with open(path, encoding='utf-8') as fh:
            for raw in fh:
                line = raw.strip()
                if not line or line.startswith('#') or '=' not in line:
                    continue
                key, _, value = line.partition('=')
                key = key.strip()
                value = value.strip().strip('"').strip("'")
                if key:
                    os.environ.setdefault(key, value)
    except FileNotFoundError:
        pass
    except PermissionError:
        pass


_UF_DEFAULTS = {
    'DF': {
        'slug': 'melhorprecodf',
        'domain': 'melhorprecodf.com.br',
        'chave_prefix': '53',
        'name': 'Melhor Preço DF',
        'region': 'Distrito Federal',
        'apple_bundle_id': 'com.melhorprecodf.app',
        'data_dir': '/var/www/html/melhorprecodf.com.br',
        'env_file': '/etc/melhorprecodf/django.env',
        'db_name': 'melhorprecodf',
        'db_user': 'melhorprecodf',
        'geocode_lat': -15.7975,
        'geocode_lng': -47.8919,
        'default_city': 'Brasília',
        'default_uf': 'DF',
    },
    'RO': {
        'slug': 'melhorprecoro',
        'domain': 'melhorprecoro.com.br',
        'chave_prefix': '11',
        'name': 'Melhor Preço RO',
        'region': 'Rondônia',
        'apple_bundle_id': 'com.melhorprecoro.app',
        'data_dir': '/var/www/html/melhorprecoro.com.br',
        'env_file': '/etc/melhorprecoro/django.env',
        'db_name': 'melhorprecoro',
        'db_user': 'melhorprecoro',
        'geocode_lat': -8.7619,
        'geocode_lng': -63.9039,
        'default_city': 'Porto Velho',
        'default_uf': 'RO',
    },
}


def _default_uf_from_path() -> str:
    """Second clone in melhorprecoro.com.br defaults to RO without extra env."""
    base = str(BASE_DIR).replace('\\', '/').lower()
    if 'melhorprecoro' in base:
        return 'RO'
    return 'DF'


# Production secrets live outside the repo (see deploy/DEPLOY.md).
# Prefer DJANGO_ENV_FILE; otherwise pick DF/RO from SITE_UF or the checkout path.
_explicit_env = os.environ.get('DJANGO_ENV_FILE', '').strip()
_uf_hint = os.environ.get('SITE_UF', _default_uf_from_path()).upper()
if _uf_hint not in _UF_DEFAULTS:
    _uf_hint = _default_uf_from_path()
if _explicit_env:
    _load_env_file(_explicit_env)
else:
    _load_env_file(_UF_DEFAULTS[_uf_hint]['env_file'])
_load_env_file(str(BASE_DIR / '.env'))

SITE_UF = os.environ.get('SITE_UF', _uf_hint).upper()
if SITE_UF not in _UF_DEFAULTS:
    SITE_UF = _uf_hint
_uf = _UF_DEFAULTS[SITE_UF]

SITE_SLUG = os.environ.get('SITE_SLUG', _uf['slug'])
SITE_DOMAIN = os.environ.get('SITE_DOMAIN', _uf['domain'])
SITE_NAME = os.environ.get('SITE_NAME', _uf['name'])
SITE_REGION = os.environ.get('SITE_REGION', _uf['region'])
CHAVE_PREFIX = os.environ.get('CHAVE_PREFIX', _uf['chave_prefix'])
DATA_DIR = os.environ.get('DATA_DIR', _uf['data_dir'])
GEOCODE_LAT = float(os.environ.get('GEOCODE_LAT', _uf['geocode_lat']))
GEOCODE_LNG = float(os.environ.get('GEOCODE_LNG', _uf['geocode_lng']))
DEFAULT_CITY = os.environ.get('DEFAULT_CITY', _uf['default_city'])
DEFAULT_UF = os.environ.get('DEFAULT_UF', _uf['default_uf'])


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get(
    'DJANGO_SECRET_KEY',
    'django-insecure-=jeg8^_3t%v$&0nu2c(5@w45njh@#*=1p&y$o*^_fzr4areu2n',
)

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

ALLOWED_HOSTS = [
    host.strip()
    for host in os.environ.get('ALLOWED_HOSTS', SITE_DOMAIN).split(',')
    if host.strip()
]


# Application definition

INSTALLED_APPS = [
    "notas.apps.NotasConfig",
    "api.apps.ApiConfig",
    "django_crontab",
    "corsheaders",
    #'django.contrib.admin',
    "core.apps.CustomAdminConfig",
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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

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


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

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": os.environ.get("DB_NAME", _uf["db_name"]),
        "USER": os.environ.get("DB_USER", _uf["db_user"]),
        "PASSWORD": os.environ.get("DB_PASSWORD", ""),
        "HOST": os.environ.get("DB_HOST", "127.0.0.1"),
        "PORT": os.environ.get("DB_PORT", "3306"),
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.1/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',
    },
]

#cronjob
CRONJOBS = [
    (
        '30 19 * * 2,4,6',
        'notas.tasks.enviar_email_programado',
        f'>> {DATA_DIR}/log_cron.log 2>&1',
    ),
]

# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'pt-BR'

TIME_ZONE = 'America/Sao_Paulo'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = '/static/'  # URL para acessar arquivos estáticos
STATICFILES_DIRS = [
    BASE_DIR / "static",  # Diretório onde estão os arquivos estáticos locais
    BASE_DIR / "notas/static",
]
STATIC_ROOT = BASE_DIR / "staticfiles"  # Diretório para collectstatic (usado em produção)


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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'AKIAVXJYEDQ75ESQDITZ'
EMAIL_HOST_PASSWORD = 'BE65rHHFIO7IOCXjoFfALs4DAV0InroCCSIOqZYeFSMz'


# ---------- Mobile API Configuration ----------

# API key used by the mobile app to authenticate requests.
# Must match the EXPO_PUBLIC_API_KEY in the app's .env file.
MOBILE_API_KEY = 'mp-app-key-a7f3b9c1d4e8f2016534'

# Google OAuth Web Client ID (same one used in the mobile app).
GOOGLE_CLIENT_ID = '142522199985-fa2qk7gj3tqnakaf26nr8ofae51qmcs8.apps.googleusercontent.com'

# Apple Sign In — used to verify the audience (aud) claim of the identity
# token sent by the iOS app. Must match the bundleIdentifier of the app.
APPLE_BUNDLE_ID = os.environ.get('APPLE_BUNDLE_ID', _uf['apple_bundle_id'])

# Google Maps Platform API Key – used server-side for Places / Geocoding.
# Must have "Places API" and "Geocoding API" enabled in the Cloud Console.
GOOGLE_MAPS_API_KEY = 'AIzaSyAAhs4Sp4Ap1rKJBJHW-oEOtNEnKvAdYgs'

# CORS — allow the mobile app to reach the API.
# In production with a native app, CORS is usually not enforced,
# but we add the domain for any web-based testing.
CORS_ALLOWED_ORIGINS = [
    f'https://{SITE_DOMAIN}',
]
CORS_ALLOW_HEADERS = [
    'accept',
    'content-type',
    'x-api-key',
    'x-auth-token',
]
