import os
import sys
from pathlib import Path
from dotenv import load_dotenv

BASE_DIR = Path(__file__).resolve().parent.parent
load_dotenv(BASE_DIR.parent / ".env", override=False)
TESTING = ("test" in sys.argv) or os.getenv("DJANGO_TESTING", "").lower() == "true"

APP_NAME = os.getenv("APP_NAME", "Maya OS")
APP_ENV = os.getenv("APP_ENV", "development").lower()
APP_VERSION = os.getenv("APP_VERSION", "3.0.0")
APP_DOMAIN = os.getenv("APP_DOMAIN", "localhost")

SECRET_KEY = os.getenv("APP_SECRET_KEY") or os.getenv(
    "DJANGO_SECRET_KEY",
    "dev-only-insecure-key-replace-in-production-maya-os-2026",
)
_debug_raw = os.getenv("APP_DEBUG") or os.getenv("DJANGO_DEBUG") or ("false" if APP_ENV == "production" else "true")
DEBUG = _debug_raw.lower() == "true"

ALLOWED_HOSTS = [
    h.strip()
    for h in (os.getenv("DJANGO_ALLOWED_HOSTS") or ("*" if DEBUG else f"{APP_DOMAIN},localhost,127.0.0.1")).split(",")
    if h.strip()
]

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Third-party
    "rest_framework",
    "django_filters",
    "drf_spectacular",
    "channels",
    # Maya OS apps
    "apps.localization",
    "apps.accounts_rbac",
    "apps.tenancy",
    "apps.audit",
    "apps.projects",
    "apps.accounting",
    "apps.sync",
    "apps.dashboard",
    "apps.navigation",
    "apps.currency",
    "apps.banking",
    "apps.loans",
    "apps.treasury",
    "apps.document_engine",
    "apps.construction_ops",
    "apps.budgeting",
    "apps.inventory",
    "apps.procurement",
    "apps.hr",
    "apps.party_hub",
    "apps.reporting",
    "apps.system_admin",
    "apps.chat",
    "apps.notifications",
    "apps.fleet",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.middleware.gzip.GZipMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "apps.system_admin.telemetry_middleware.EnterpriseTelemetryAndSecurityMiddleware",
    "apps.system_admin.middleware.MaintenanceAndSessionPolicyMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "config.urls"

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

# Authoritative MySQL 8.4 LTS Database Configuration (InnoDB, utf8mb4, READ COMMITTED)
DB_ENGINE = os.getenv("DB_ENGINE", "mysql").lower()
if DB_ENGINE != "mysql":
    raise RuntimeError(
        f"Unsupported DB_ENGINE='{DB_ENGINE}'. Maya OS Enterprise is MySQL-authoritative; set DB_ENGINE=mysql."
    )

DB_CONN_MAX_AGE = int(os.getenv("MYSQL_CONN_MAX_AGE", os.getenv("DB_CONN_MAX_AGE", "30")))
_mysql_init_sql = (
    "SET SESSION sql_mode='STRICT_TRANS_TABLES,STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION', "
    "SESSION transaction_isolation='READ-COMMITTED'"
)
if os.getenv("MYSQL_FORCE_INNODB", "true").lower() == "true":
    _mysql_init_sql += ", SESSION default_storage_engine='InnoDB'"

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": os.environ.get("MYSQL_DATABASE", "maya_os"),
        "USER": os.environ.get("MYSQL_USER", "root"),
        "PASSWORD": os.environ.get("MYSQL_PASSWORD", ""),
        "HOST": os.environ.get("MYSQL_HOST", "127.0.0.1"),
        "PORT": os.environ.get("MYSQL_PORT", "3306"),
        "CONN_MAX_AGE": DB_CONN_MAX_AGE,
        "CONN_HEALTH_CHECKS": True,
        "OPTIONS": {
            "charset": os.getenv("MYSQL_CHARSET", "utf8mb4"),
            "connect_timeout": int(os.getenv("MYSQL_CONNECT_TIMEOUT", "10")),
            "read_timeout": int(os.getenv("MYSQL_READ_TIMEOUT", "30")),
            "write_timeout": int(os.getenv("MYSQL_WRITE_TIMEOUT", "30")),
            "init_command": _mysql_init_sql,
        },
    }
}

if os.getenv("MYSQL_REPLICA_HOST"):
    DATABASES["replica"] = {
        **DATABASES["default"],
        "HOST": os.environ["MYSQL_REPLICA_HOST"],
        "PORT": os.environ.get("MYSQL_REPLICA_PORT", os.environ.get("MYSQL_PORT", "3306")),
    }

DATABASE_ROUTERS = ["apps.system_admin.db_router.ReportingReplicaRouter"]

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

AUTH_USER_MODEL = "accounts_rbac.User"

AUTH_PASSWORD_VALIDATORS = [
    {"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", "OPTIONS": {"min_length": 10}},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

LANGUAGE_CODE = "en-us"
TIME_ZONE = os.getenv("APP_TIME_ZONE", "Asia/Kathmandu")
USE_I18N = True
USE_TZ = True

STATIC_URL = "static/"
STATIC_ROOT = Path(os.getenv("STATIC_ROOT", str(BASE_DIR / "staticfiles")))
MEDIA_ROOT = Path(os.getenv("MEDIA_ROOT", str(BASE_DIR / "media")))
BACKUP_ROOT = Path(os.getenv("BACKUP_ROOT", str(BASE_DIR / "backups")))

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

# Session, Proxy & Cookie Security
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
USE_X_FORWARDED_HOST = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SAMESITE = "Lax"
SESSION_COOKIE_SECURE = os.getenv("SESSION_COOKIE_SECURE", "true" if (APP_ENV == "production" and not DEBUG) else "false").lower() == "true"
CSRF_COOKIE_SAMESITE = "Lax"
CSRF_COOKIE_SECURE = os.getenv("CSRF_COOKIE_SECURE", "true" if (APP_ENV == "production" and not DEBUG) else "false").lower() == "true"
SECURE_SSL_REDIRECT = os.getenv("SECURE_SSL_REDIRECT", "true" if (APP_ENV == "production" and not DEBUG and not TESTING) else "false").lower() == "true"
CSRF_TRUSTED_ORIGINS = [
    o.strip()
    for o in os.getenv(
        "CSRF_TRUSTED_ORIGINS", f"https://{APP_DOMAIN},http://localhost:8080,http://localhost:5173"
    ).split(",")
    if o.strip()
]

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication",
    ],
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",
    ],
    "DEFAULT_FILTER_BACKENDS": [
        "django_filters.rest_framework.DjangoFilterBackend",
        "rest_framework.filters.SearchFilter",
        "rest_framework.filters.OrderingFilter",
    ],
    "DEFAULT_THROTTLE_CLASSES": [
        "rest_framework.throttling.AnonRateThrottle",
        "rest_framework.throttling.UserRateThrottle",
        "rest_framework.throttling.ScopedRateThrottle",
    ],
    "DEFAULT_THROTTLE_RATES": {
        "anon": "5000/min" if TESTING else os.getenv("DRF_THROTTLE_ANON", "120/min"),
        "user": "10000/min" if TESTING else os.getenv("DRF_THROTTLE_USER", "900/min"),
        "login": "1000/min" if TESTING else os.getenv("DRF_THROTTLE_LOGIN", "15/min"),
        "staff_code_login": "1000/min" if TESTING else os.getenv("DRF_THROTTLE_STAFF_CODE", "8/min"),
        "heavy_export": "1000/min" if TESTING else os.getenv("DRF_THROTTLE_EXPORT", "30/min"),
    },
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 50,
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
    "COERCE_DECIMAL_TO_STRING": True,
    "EXCEPTION_HANDLER": "apps.system_admin.telemetry_middleware.enterprise_exception_handler",
}

SPECTACULAR_SETTINGS = {
    "TITLE": "Maya OS Enterprise Construction Accounting API",
    "DESCRIPTION": "Server-authoritative double-entry accounting, construction job costing, and offline sync API.",
    "VERSION": APP_VERSION,
}

DATA_UPLOAD_MAX_MEMORY_SIZE = 20 * 1024 * 1024
FILE_UPLOAD_MAX_MEMORY_SIZE = 10 * 1024 * 1024
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = "DENY"
SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin"
if not DEBUG:
    SECURE_HSTS_SECONDS = int(os.getenv("SECURE_HSTS_SECONDS", "31536000"))
    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_PRELOAD = True

REDIS_URL = os.getenv("REDIS_URL", "")
USE_REDIS = bool(REDIS_URL) and (not TESTING or os.getenv("FORCE_REDIS", "false").lower() == "true")

if USE_REDIS:
    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.redis.RedisCache",
            "LOCATION": REDIS_URL,
            "KEY_PREFIX": "maya_os",
        }
    }
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels_redis.core.RedisChannelLayer",
            "CONFIG": {
                "hosts": [REDIS_URL],
                "capacity": 1500,
                "expiry": 15,
            },
        }
    }
else:
    CACHES = {
        "default": {
            "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
            "LOCATION": "maya-os-local-cache",
        }
    }
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
        }
    }

CELERY_BROKER_URL = os.getenv("CELERY_BROKER_URL", "redis://localhost:6379/0")
CELERY_RESULT_BACKEND = os.getenv("CELERY_RESULT_BACKEND", "redis://localhost:6379/1")
CELERY_TIMEZONE = TIME_ZONE
CELERY_TASK_ACKS_LATE = True
CELERY_WORKER_PREFETCH_MULTIPLIER = 1
CELERY_TASK_DEFAULT_QUEUE = "critical_accounting"
CELERY_TASK_ROUTES = {
    "apps.accounting.*": {"queue": "critical_accounting"},
    "apps.banking.*": {"queue": "bank_treasury"},
    "apps.treasury.*": {"queue": "bank_treasury"},
    "apps.loans.*": {"queue": "bank_treasury"},
    "apps.reporting.*": {"queue": "reports_exports"},
    "apps.document_engine.*": {"queue": "reports_exports"},
    "apps.system_admin.tasks.run_scheduled_backup*": {"queue": "backup_recovery"},
    "apps.system_admin.*": {"queue": "maintenance_scheduled"},
    "apps.chat.*": {"queue": "chat_notifications"},
    "apps.notifications.*": {"queue": "chat_notifications"},
}

PRIVATE_DOCUMENT_ROOT = Path(os.getenv("PRIVATE_DOCUMENT_ROOT", str(BASE_DIR / "private_documents")))
DOCUMENT_STORAGE_BACKEND = os.getenv("DOCUMENT_STORAGE_BACKEND", "local_encrypted")
DOCUMENT_ASYNC_EAGER = os.getenv("DOCUMENT_ASYNC_EAGER", "true" if DEBUG else "false").lower() == "true"

EMAIL_HOST = os.getenv("EMAIL_HOST", "")
EMAIL_PORT = int(os.getenv("EMAIL_PORT", "587"))
EMAIL_USE_TLS = os.getenv("EMAIL_USE_TLS", "true").lower() == "true"
EMAIL_HOST_USER = os.getenv("EMAIL_USER", "")
EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PASSWORD", "")
DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL", f"noreply@{APP_DOMAIN}")

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {
            "format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        },
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "standard",
        },
    },
    "root": {
        "handlers": ["console"],
        "level": os.getenv("LOG_LEVEL", "INFO"),
    },
}
