"""Shared configuration and clients for the backend.

Centralizes environment loading, logging configuration, Supabase clients,
and Stripe configuration so other modules can import from a single place.
"""

from __future__ import annotations

import logging
import os
from datetime import UTC
from pathlib import Path

import stripe
from dotenv import load_dotenv
from supabase import create_client

from backend.utils.logger import logger

# Load environment variables from saas-platform/.env
# Use absolute path relative to this file's location
config_dir = Path(__file__).parent
saas_platform_env = config_dir / "../../../.env"
load_dotenv(saas_platform_env)

# Configure logging once
logging.basicConfig(level=logging.INFO)


def _get_secret(name: str, default: str = "") -> str:
    """Return secret from env or file .

    If `NAME` not set, but `NAME_FILE` points to a readable file, read its
    contents and return the stripped value. Otherwise return default.
    """
    val = os.getenv(name)
    if val:
        return val
    file_var = f"{name}_FILE"
    file_path = os.getenv(file_var)
    if file_path and Path(file_path).exists():
        try:
            with Path(file_path).open(encoding="utf-8") as fh:
                return fh.read().strip()
        except Exception:
            logger.warning("Failed reading secret file for %s", name)
    return default


# Initialize Supabase (service client bypasses RLS)
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_SERVICE_KEY = _get_secret("SUPABASE_SERVICE_KEY")
SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY")

if SUPABASE_URL and SUPABASE_SERVICE_KEY:
    supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
    auth_client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
else:
    logger.warning("Supabase not configured: missing SUPABASE_URL or SUPABASE_SERVICE_KEY")
    supabase = None  # type: ignore[assignment]
    auth_client = None  # type: ignore[assignment]

# Platform configuration
PLATFORM_DOMAIN = os.getenv("PLATFORM_DOMAIN", "mindroom.chat")
ENVIRONMENT = os.getenv("ENVIRONMENT", "production")
ENABLE_CLEANUP_SCHEDULER = os.getenv("ENABLE_CLEANUP_SCHEDULER", "false").lower() in {"1", "true", "yes"}

# Stripe configuration
stripe.api_key = _get_secret("STRIPE_SECRET_KEY", "")
STRIPE_WEBHOOK_SECRET = _get_secret("STRIPE_WEBHOOK_SECRET", "")

# Provisioner API key for internal provisioning actions
PROVISIONER_API_KEY = _get_secret("PROVISIONER_API_KEY", "")
INSTANCE_BASE_DOMAIN = os.getenv("INSTANCE_BASE_DOMAIN", PLATFORM_DOMAIN)
INSTANCE_STORAGE_CLASS_NAME = os.getenv("INSTANCE_STORAGE_CLASS_NAME", "")
INSTANCE_MINDROOM_IMAGE = os.getenv("INSTANCE_MINDROOM_IMAGE", "")
INSTANCE_MINDROOM_IMAGE_PULL_POLICY = os.getenv("INSTANCE_MINDROOM_IMAGE_PULL_POLICY", "")
INSTANCE_IMAGE_PULL_SECRET_NAMES = os.getenv("INSTANCE_IMAGE_PULL_SECRET_NAMES", "")
INSTANCE_MATRIX_HOMESERVER_STARTUP_TIMEOUT_SECONDS = os.getenv("INSTANCE_MATRIX_HOMESERVER_STARTUP_TIMEOUT_SECONDS", "")
INSTANCE_CREDENTIALS_ENCRYPTION_SECRET = _get_secret("INSTANCE_CREDENTIALS_ENCRYPTION_SECRET", "")
INSTANCE_SYNAPSE_IMAGE = os.getenv("INSTANCE_SYNAPSE_IMAGE", "")
INSTANCE_SYNAPSE_IMAGE_PULL_POLICY = os.getenv("INSTANCE_SYNAPSE_IMAGE_PULL_POLICY", "")
INSTANCE_TRUSTED_UPSTREAM_AUTH_ENABLED = os.getenv("INSTANCE_TRUSTED_UPSTREAM_AUTH_ENABLED", "")
INSTANCE_TRUSTED_UPSTREAM_USER_ID_HEADER = os.getenv("INSTANCE_TRUSTED_UPSTREAM_USER_ID_HEADER", "")
INSTANCE_TRUSTED_UPSTREAM_EMAIL_HEADER = os.getenv("INSTANCE_TRUSTED_UPSTREAM_EMAIL_HEADER", "")
INSTANCE_TRUSTED_UPSTREAM_MATRIX_USER_ID_HEADER = os.getenv("INSTANCE_TRUSTED_UPSTREAM_MATRIX_USER_ID_HEADER", "")
INSTANCE_TRUSTED_UPSTREAM_EMAIL_TO_MATRIX_USER_ID_TEMPLATE = os.getenv(
    "INSTANCE_TRUSTED_UPSTREAM_EMAIL_TO_MATRIX_USER_ID_TEMPLATE", ""
)
INSTANCE_TRUSTED_UPSTREAM_REQUIRE_JWT = os.getenv("INSTANCE_TRUSTED_UPSTREAM_REQUIRE_JWT", "")
INSTANCE_TRUSTED_UPSTREAM_JWT_HEADER = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWT_HEADER", "")
INSTANCE_TRUSTED_UPSTREAM_JWKS_URL = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWKS_URL", "")
INSTANCE_TRUSTED_UPSTREAM_JWT_AUDIENCE = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWT_AUDIENCE", "")
INSTANCE_TRUSTED_UPSTREAM_JWT_ISSUER = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWT_ISSUER", "")
INSTANCE_TRUSTED_UPSTREAM_JWT_EMAIL_CLAIM = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWT_EMAIL_CLAIM", "")
INSTANCE_TRUSTED_UPSTREAM_JWT_USER_ID_CLAIM = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWT_USER_ID_CLAIM", "")
INSTANCE_TRUSTED_UPSTREAM_JWT_MATRIX_USER_ID_CLAIM = os.getenv("INSTANCE_TRUSTED_UPSTREAM_JWT_MATRIX_USER_ID_CLAIM", "")

# First-party OIDC issuer used by hosted Synapse instances for Matrix SSO.
MATRIX_OIDC_ENABLED = os.getenv("MATRIX_OIDC_ENABLED", "false").lower() in {"1", "true", "yes"}
MATRIX_OIDC_ISSUER = os.getenv("MATRIX_OIDC_ISSUER", "")
MATRIX_OIDC_CLIENT_ID = os.getenv("MATRIX_OIDC_CLIENT_ID", "mindroom-synapse")
MATRIX_OIDC_CLIENT_SECRET = _get_secret("MATRIX_OIDC_CLIENT_SECRET", "")
MATRIX_OIDC_PRIVATE_KEY = _get_secret("MATRIX_OIDC_PRIVATE_KEY", "")
MATRIX_OIDC_KEY_ID = os.getenv("MATRIX_OIDC_KEY_ID", "mindroom-platform")

INSTANCE_MATRIX_OIDC_ENABLED = os.getenv("INSTANCE_MATRIX_OIDC_ENABLED", "")
INSTANCE_MATRIX_OIDC_ISSUER = os.getenv("INSTANCE_MATRIX_OIDC_ISSUER", "")
INSTANCE_MATRIX_OIDC_CLIENT_ID = os.getenv("INSTANCE_MATRIX_OIDC_CLIENT_ID", "")
INSTANCE_MATRIX_OIDC_CLIENT_SECRET = _get_secret("INSTANCE_MATRIX_OIDC_CLIENT_SECRET", "")

# API keys for MindRoom instances (shared across customers for now)
OPENAI_API_KEY = _get_secret("OPENAI_API_KEY", "")
ANTHROPIC_API_KEY = _get_secret("ANTHROPIC_API_KEY", "")
GOOGLE_API_KEY = _get_secret("GOOGLE_API_KEY", "")
OPENROUTER_API_KEY = _get_secret("OPENROUTER_API_KEY", "")
OPENROUTER_PROVISIONING_API_KEY = _get_secret("OPENROUTER_PROVISIONING_API_KEY", "")
DEEPSEEK_API_KEY = _get_secret("DEEPSEEK_API_KEY", "")
SANDBOX_PROXY_TOKEN = _get_secret("SANDBOX_PROXY_TOKEN", "")


def _build_allowed_origins(domain: str, environment: str) -> list[str]:
    """Compute allowed CORS origins from superdomain and environment.

    Always allow the platform app origin. Include localhost origins in
    non-production environments to ease development.
    Additional origins can be supplied via comma-separated ALLOWED_ORIGINS env.
    """
    origins = [f"https://app.{domain}"]

    if environment != "production":
        origins += ["http://localhost:3000", "http://localhost:3001"]

    extra = os.getenv("ALLOWED_ORIGINS", "").strip()
    if extra:
        origins += [o.strip() for o in extra.split(",") if o.strip()]

    return origins


# CORS allowed origins
ALLOWED_ORIGINS = _build_allowed_origins(PLATFORM_DOMAIN, ENVIRONMENT)

__all__ = [
    "ALLOWED_ORIGINS",
    "ENABLE_CLEANUP_SCHEDULER",
    "ENVIRONMENT",
    "INSTANCE_BASE_DOMAIN",
    "INSTANCE_CREDENTIALS_ENCRYPTION_SECRET",
    "INSTANCE_IMAGE_PULL_SECRET_NAMES",
    "INSTANCE_MATRIX_HOMESERVER_STARTUP_TIMEOUT_SECONDS",
    "INSTANCE_MINDROOM_IMAGE",
    "INSTANCE_MINDROOM_IMAGE_PULL_POLICY",
    "INSTANCE_SYNAPSE_IMAGE",
    "INSTANCE_SYNAPSE_IMAGE_PULL_POLICY",
    "INSTANCE_STORAGE_CLASS_NAME",
    "INSTANCE_TRUSTED_UPSTREAM_AUTH_ENABLED",
    "INSTANCE_TRUSTED_UPSTREAM_EMAIL_TO_MATRIX_USER_ID_TEMPLATE",
    "INSTANCE_TRUSTED_UPSTREAM_EMAIL_HEADER",
    "INSTANCE_TRUSTED_UPSTREAM_JWKS_URL",
    "INSTANCE_TRUSTED_UPSTREAM_JWT_AUDIENCE",
    "INSTANCE_TRUSTED_UPSTREAM_JWT_EMAIL_CLAIM",
    "INSTANCE_TRUSTED_UPSTREAM_JWT_HEADER",
    "INSTANCE_TRUSTED_UPSTREAM_JWT_ISSUER",
    "INSTANCE_TRUSTED_UPSTREAM_JWT_MATRIX_USER_ID_CLAIM",
    "INSTANCE_TRUSTED_UPSTREAM_JWT_USER_ID_CLAIM",
    "INSTANCE_TRUSTED_UPSTREAM_MATRIX_USER_ID_HEADER",
    "INSTANCE_TRUSTED_UPSTREAM_REQUIRE_JWT",
    "INSTANCE_TRUSTED_UPSTREAM_USER_ID_HEADER",
    "INSTANCE_MATRIX_OIDC_CLIENT_ID",
    "INSTANCE_MATRIX_OIDC_CLIENT_SECRET",
    "INSTANCE_MATRIX_OIDC_ENABLED",
    "INSTANCE_MATRIX_OIDC_ISSUER",
    "MATRIX_OIDC_CLIENT_ID",
    "MATRIX_OIDC_CLIENT_SECRET",
    "MATRIX_OIDC_ENABLED",
    "MATRIX_OIDC_ISSUER",
    "MATRIX_OIDC_KEY_ID",
    "MATRIX_OIDC_PRIVATE_KEY",
    "PLATFORM_DOMAIN",
    "PROVISIONER_API_KEY",
    "OPENROUTER_PROVISIONING_API_KEY",
    "STRIPE_WEBHOOK_SECRET",
    "SUPABASE_ANON_KEY",
    "SUPABASE_URL",
    "UTC",
    "auth_client",
    "logger",
    "stripe",
    "supabase",
]
