from os import getenv
from urllib.parse import urlparse

trues = ("t", "true", "yes", "y", "1")


def _csv_env(name: str, default: str) -> list[str]:
    return [item.strip() for item in getenv(name, default).split(",") if item.strip()]


# URLs
DOMAIN = getenv("DOMAIN", "example.com")
URL = getenv("URL", f"https://{DOMAIN}")
URL_HOST = urlparse(URL).hostname or ""
DEBUG = getenv("DEBUG", "false").lower() in trues

# Access control
ALLOWED_HOSTS = _csv_env(
    "ALLOWED_HOSTS",
    ",".join(
        item
        for item in (
            "localhost",
            "127.0.0.1",
            DOMAIN,
            URL_HOST,
        )
        if item
    ),
)
if DEBUG:
    # Local/dev stack runs behind varying hostnames/tunnels.
    ALLOWED_HOSTS = ["*"]

# CSRF
CSRF_TRUSTED_ORIGINS = _csv_env("CSRF_TRUSTED_ORIGINS", URL)

# Stripe
BILLING_ENABLED = getenv("BILLING_ENABLED", "false").lower() in trues
STRIPE_TEST = getenv("STRIPE_TEST", "true") in trues
STRIPE_API_KEY_TEST = getenv("STRIPE_API_KEY_TEST", "")
STRIPE_PUBLIC_API_KEY_TEST = getenv("STRIPE_PUBLIC_API_KEY_TEST", "")

STRIPE_API_KEY_PROD = getenv("STRIPE_API_KEY_PROD", "")
STRIPE_PUBLIC_API_KEY_PROD = getenv("STRIPE_PUBLIC_API_KEY_PROD", "")

STRIPE_ENDPOINT_SECRET = getenv("STRIPE_ENDPOINT_SECRET", "")
STATIC_ROOT = getenv("STATIC_ROOT", "")
SECRET_KEY = (getenv("SECRET_KEY", "") or "").strip()
if not SECRET_KEY:
    # Keep local developer stacks usable when stack.env is uninitialized.
    SECRET_KEY = "gia-dev-secret-key"

STRIPE_ADMIN_COUPON = getenv("STRIPE_ADMIN_COUPON", "")

REGISTRATION_OPEN = getenv("REGISTRATION_OPEN", "false").lower() in trues

LAGO_API_KEY = getenv("LAGO_API_KEY", "")
LAGO_ORG_ID = getenv("LAGO_ORG_ID", "")
LAGO_URL = getenv("LAGO_URL", "")

PROFILER = getenv("PROFILER", "false") in trues

if DEBUG:
    import socket  # only if you haven't already imported this

    hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())
    INTERNAL_IPS = [ip[: ip.rfind(".")] + ".1" for ip in ips]
    INTERNAL_IPS.extend(
        [
            item.strip()
            for item in getenv("DEBUG_INTERNAL_IPS", "localhost").split(",")
            if item.strip()
        ]
    )

SETTINGS_EXPORT = ["BILLING_ENABLED"]

SIGNAL_NUMBER = getenv("SIGNAL_NUMBER")
SIGNAL_HTTP_URL = getenv("SIGNAL_HTTP_URL", "http://signal:8080")

WHATSAPP_ENABLED = getenv("WHATSAPP_ENABLED", "false").lower() in trues
WHATSAPP_HTTP_URL = getenv("WHATSAPP_HTTP_URL", "http://whatsapp:8080")

INSTAGRAM_ENABLED = getenv("INSTAGRAM_ENABLED", "false").lower() in trues
INSTAGRAM_HTTP_URL = getenv("INSTAGRAM_HTTP_URL", "http://instagram:8080")

XMPP_ADDRESS = getenv("XMPP_ADDRESS")
XMPP_JID = getenv("XMPP_JID")
XMPP_USER_DOMAIN = getenv("XMPP_USER_DOMAIN", "")
XMPP_PORT = int(getenv("XMPP_PORT", "8888") or 8888)
XMPP_SECRET = getenv("XMPP_SECRET")
XMPP_OMEMO_DATA_DIR = getenv("XMPP_OMEMO_DATA_DIR", "")
XMPP_UPLOAD_SERVICE = getenv("XMPP_UPLOAD_SERVICE", "").strip()
XMPP_UPLOAD_JID = getenv("XMPP_UPLOAD_JID", "").strip()
if not XMPP_UPLOAD_SERVICE and XMPP_UPLOAD_JID:
    XMPP_UPLOAD_SERVICE = XMPP_UPLOAD_JID
if not XMPP_UPLOAD_SERVICE and XMPP_USER_DOMAIN:
    XMPP_UPLOAD_SERVICE = XMPP_USER_DOMAIN

EVENT_LEDGER_DUAL_WRITE = getenv("EVENT_LEDGER_DUAL_WRITE", "false").lower() in trues
CAPABILITY_ENFORCEMENT_ENABLED = (
    getenv("CAPABILITY_ENFORCEMENT_ENABLED", "true").lower() in trues
)
TRACE_PROPAGATION_ENABLED = getenv("TRACE_PROPAGATION_ENABLED", "true").lower() in trues
EVENT_PRIMARY_WRITE_PATH = getenv("EVENT_PRIMARY_WRITE_PATH", "false").lower() in trues

MEMORY_SEARCH_BACKEND = getenv("MEMORY_SEARCH_BACKEND", "django")
MANTICORE_HTTP_URL = getenv("MANTICORE_HTTP_URL", "http://localhost:9308")
MANTICORE_MEMORY_TABLE = getenv("MANTICORE_MEMORY_TABLE", "gia_memory_items")
MANTICORE_EVENT_TABLE = getenv("MANTICORE_EVENT_TABLE", "gia_events")
MANTICORE_METRIC_TABLE = getenv("MANTICORE_METRIC_TABLE", "gia_metrics")
COMPOSING_ABANDONED_WINDOW_SECONDS = int(
    getenv("COMPOSING_ABANDONED_WINDOW_SECONDS", "300")
)
CONVERSATION_EVENT_RETENTION_DAYS = int(
    getenv("CONVERSATION_EVENT_RETENTION_DAYS", "90") or 90
)
MANTICORE_HTTP_TIMEOUT = int(getenv("MANTICORE_HTTP_TIMEOUT", "5") or 5)

# Attachment security defaults for transport adapters.
ATTACHMENT_MAX_BYTES = int(getenv("ATTACHMENT_MAX_BYTES", str(25 * 1024 * 1024)) or 0)
ATTACHMENT_ALLOW_PRIVATE_URLS = (
    getenv("ATTACHMENT_ALLOW_PRIVATE_URLS", "false").lower() in trues
)
ATTACHMENT_ALLOW_UNKNOWN_MIME = (
    getenv("ATTACHMENT_ALLOW_UNKNOWN_MIME", "false").lower() in trues
)
