from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=None, extra="ignore")

    app_env: str = Field(default="dev", alias="APP_ENV")
    installation_id: str = Field(
        default="govoplan-local",
        alias="GOVOPLAN_INSTALLATION_ID",
    )
    state_profile: str = Field(
        default="local",
        alias="GOVOPLAN_STATE_PROFILE",
    )
    runtime_role: str = Field(default="api", alias="GOVOPLAN_RUNTIME_ROLE")
    runtime_node_id: str | None = Field(default=None, alias="GOVOPLAN_NODE_ID")
    runtime_heartbeat_seconds: int = Field(
        default=15,
        ge=2,
        le=300,
        alias="GOVOPLAN_RUNTIME_HEARTBEAT_SECONDS",
    )
    runtime_stale_after_seconds: int = Field(
        default=60,
        ge=10,
        le=3600,
        alias="GOVOPLAN_RUNTIME_STALE_AFTER_SECONDS",
    )
    runtime_expected_api_replicas: int = Field(
        default=1,
        ge=1,
        le=1000,
        alias="GOVOPLAN_EXPECTED_API_REPLICAS",
    )
    runtime_expected_worker_replicas: int = Field(
        default=0,
        ge=0,
        le=1000,
        alias="GOVOPLAN_EXPECTED_WORKER_REPLICAS",
    )
    module_live_apply_enabled: bool | None = Field(
        default=None,
        alias="GOVOPLAN_MODULE_LIVE_APPLY_ENABLED",
    )

    database_url: str = Field(
        default="postgresql+psycopg://govoplan_dev@127.0.0.1:5432/govoplan_dev",
        alias="DATABASE_URL",
    )
    database_pool_size: int = Field(
        default=5,
        alias="GOVOPLAN_DB_POOL_SIZE",
        ge=1,
        le=100,
    )
    database_max_overflow: int = Field(
        default=10,
        alias="GOVOPLAN_DB_MAX_OVERFLOW",
        ge=0,
        le=200,
    )
    database_pool_timeout_seconds: int = Field(
        default=30,
        alias="GOVOPLAN_DB_POOL_TIMEOUT_SECONDS",
        ge=1,
        le=300,
    )
    database_pool_recycle_seconds: int = Field(
        default=1800,
        alias="GOVOPLAN_DB_POOL_RECYCLE_SECONDS",
        ge=0,
        le=86_400,
    )
    access_database_url: str | None = Field(default=None, alias="ACCESS_DATABASE_URL")
    access_db_schema: str | None = Field(default=None, alias="ACCESS_DB_SCHEMA")
    access_table_prefix: str = Field(default="access_", alias="ACCESS_TABLE_PREFIX")
    tenant_data_mode: str = Field(default="shared", alias="TENANT_DATA_MODE")
    tenant_db_url_template: str | None = Field(default=None, alias="TENANT_DB_URL_TEMPLATE")
    tenant_schema_template: str | None = Field(default=None, alias="TENANT_SCHEMA_TEMPLATE")
    enabled_modules: str = Field(
        default=(
            "tenancy,organizations,identity,idm,access,admin,dashboard,policy,"
            "audit,campaigns,files,mail,calendar,poll,scheduling,connectors,"
            "datasources,dataflow,dist_lists,workflow_engine,workflow,views,search,risk_compliance,"
            "postbox,notifications,docs,ops"
        ),
        alias="ENABLED_MODULES",
    )
    migration_track: str = Field(default="release", alias="GOVOPLAN_MIGRATION_TRACK")
    redis_url: str = Field(default="redis://redis:6379/0", alias="REDIS_URL")
    celery_enabled: bool = Field(default=False, alias="CELERY_ENABLED")

    s3_endpoint_url: str = Field(default="http://garage:3900", alias="S3_ENDPOINT_URL")
    s3_region: str = Field(default="garage", alias="S3_REGION")
    s3_access_key_id: str = Field(default="GKgovoplandev0000000000000000000", alias="S3_ACCESS_KEY_ID")
    s3_secret_access_key: str = Field(default="govoplan-dev-secret-change-me", alias="S3_SECRET_ACCESS_KEY")
    s3_bucket: str = Field(default="attachments", alias="S3_BUCKET")

    # Managed file storage. Development defaults to local filesystem storage;
    # production can switch to Garage/S3 without changing API contracts.
    file_storage_backend: str = Field(default="local", alias="FILE_STORAGE_BACKEND")
    file_storage_local_root: str = Field(default="runtime/files", alias="FILE_STORAGE_LOCAL_ROOT")
    file_storage_local_fallback_roots: str = Field(default="", alias="FILE_STORAGE_LOCAL_FALLBACK_ROOTS")
    file_storage_s3_endpoint_url: str | None = Field(default=None, alias="FILE_STORAGE_S3_ENDPOINT_URL")
    file_storage_s3_region: str | None = Field(default=None, alias="FILE_STORAGE_S3_REGION")
    file_storage_s3_access_key_id: str | None = Field(default=None, alias="FILE_STORAGE_S3_ACCESS_KEY_ID")
    file_storage_s3_secret_access_key: str | None = Field(default=None, alias="FILE_STORAGE_S3_SECRET_ACCESS_KEY")
    file_storage_s3_bucket: str | None = Field(default="files", alias="FILE_STORAGE_S3_BUCKET")
    file_storage_s3_deployment_managed: bool = Field(
        default=False,
        alias="FILE_STORAGE_S3_DEPLOYMENT_MANAGED",
    )
    file_storage_s3_endpoint_trusted: bool = Field(
        default=False,
        alias="FILE_STORAGE_S3_ENDPOINT_TRUSTED",
    )
    file_upload_max_bytes: int = Field(default=50 * 1024 * 1024, alias="FILE_UPLOAD_MAX_BYTES")
    file_upload_zip_max_bytes: int = Field(default=250 * 1024 * 1024, alias="FILE_UPLOAD_ZIP_MAX_BYTES")
    file_archive_max_entries: int = Field(default=10_000, ge=1, alias="FILE_ARCHIVE_MAX_ENTRIES")
    file_archive_max_expanded_bytes: int = Field(
        default=2 * 1024 * 1024 * 1024,
        ge=1,
        alias="FILE_ARCHIVE_MAX_EXPANDED_BYTES",
    )
    file_archive_max_expansion_ratio: int = Field(
        default=100,
        ge=1,
        alias="FILE_ARCHIVE_MAX_EXPANSION_RATIO",
    )
    file_archive_preview_ttl_seconds: int = Field(
        default=30 * 60,
        ge=60,
        alias="FILE_ARCHIVE_PREVIEW_TTL_SECONDS",
    )

    auth_session_cookie_name: str = Field(default="govoplan_session", alias="AUTH_SESSION_COOKIE_NAME")
    auth_csrf_cookie_name: str = Field(default="govoplan_csrf", alias="AUTH_CSRF_COOKIE_NAME")
    auth_cookie_secure: bool = Field(default=False, alias="AUTH_COOKIE_SECURE")
    auth_cookie_samesite: str = Field(default="lax", alias="AUTH_COOKIE_SAMESITE")
    auth_cookie_domain: str | None = Field(default=None, alias="AUTH_COOKIE_DOMAIN")
    auth_session_hours: int = Field(default=12, alias="AUTH_SESSION_HOURS")
    auth_activity_touch_interval_seconds: int = Field(
        default=5 * 60,
        ge=0,
        alias="AUTH_ACTIVITY_TOUCH_INTERVAL_SECONDS",
    )
    auth_principal_cache_enabled: bool = Field(
        default=True,
        alias="AUTH_PRINCIPAL_CACHE_ENABLED",
    )
    auth_principal_cache_session_ttl_seconds: int = Field(
        default=30,
        ge=0,
        le=300,
        alias="AUTH_PRINCIPAL_CACHE_SESSION_TTL_SECONDS",
    )
    auth_principal_cache_api_key_ttl_seconds: int = Field(
        default=10,
        ge=0,
        le=300,
        alias="AUTH_PRINCIPAL_CACHE_API_KEY_TTL_SECONDS",
    )
    auth_principal_cache_max_entries: int = Field(
        default=2048,
        ge=1,
        le=100_000,
        alias="AUTH_PRINCIPAL_CACHE_MAX_ENTRIES",
    )
    auth_login_throttle_enabled: bool = Field(default=True, alias="AUTH_LOGIN_THROTTLE_ENABLED")
    auth_login_throttle_identity_limit: int = Field(
        default=10,
        ge=1,
        alias="AUTH_LOGIN_THROTTLE_IDENTITY_LIMIT",
    )
    auth_login_throttle_client_limit: int = Field(
        default=100,
        ge=1,
        alias="AUTH_LOGIN_THROTTLE_CLIENT_LIMIT",
    )
    auth_login_throttle_window_seconds: int = Field(
        default=15 * 60,
        ge=1,
        alias="AUTH_LOGIN_THROTTLE_WINDOW_SECONDS",
    )
    auth_login_throttle_redis_retry_seconds: int = Field(
        default=30,
        ge=1,
        alias="AUTH_LOGIN_THROTTLE_REDIS_RETRY_SECONDS",
    )

    master_key_b64: str | None = Field(default=None, alias="MASTER_KEY_B64")
    celery_queues: str = Field(
        default=(
            "send_email,append_sent,notifications,mail,calendar,"
            "dataflow,workflow,postbox,events,idm,default"
        ),
        alias="CELERY_QUEUES",
    )
    calendar_outbox_terminal_retention_days: int = Field(
        default=90,
        ge=0,
        alias="CALENDAR_OUTBOX_TERMINAL_RETENTION_DAYS",
    )
    platform_event_outbox_max_attempts: int = Field(
        default=8,
        ge=1,
        le=100,
        alias="PLATFORM_EVENT_OUTBOX_MAX_ATTEMPTS",
    )
    platform_event_outbox_terminal_retention_days: int = Field(
        default=90,
        ge=0,
        alias="PLATFORM_EVENT_OUTBOX_TERMINAL_RETENTION_DAYS",
    )
    scheduling_cancellation_notice_days: int = Field(
        default=30,
        ge=1,
        le=90,
        alias="SCHEDULING_CANCELLATION_NOTICE_DAYS",
    )
    mock_mailbox_dir: str = Field(default="runtime/mock-mailbox", alias="MOCK_MAILBOX_DIR")

    # Development bootstrap only. Do not use this in production.
    dev_bootstrap_api_key: str | None = Field(default="dev-govoplan-api-key", alias="DEV_BOOTSTRAP_API_KEY")
    dev_auto_migrate_enabled: bool = Field(default=True, alias="DEV_AUTO_MIGRATE_ENABLED")
    dev_bootstrap_enabled: bool = Field(default=False, alias="DEV_BOOTSTRAP_ENABLED")
    dev_bootstrap_password: str = Field(default="dev-admin", alias="DEV_BOOTSTRAP_PASSWORD")
    dev_mailbox_api_enabled: bool = Field(default=False, alias="DEV_MAILBOX_API_ENABLED")

    # Comma-separated list. Use * only for local development.
    cors_origins: str = Field(default="http://localhost:5173,http://127.0.0.1:5173,http://localhost:8080", alias="CORS_ORIGINS")


settings = Settings()
