"""Configuration for waft_client."""

from __future__ import annotations

import os
import secrets
from dataclasses import dataclass, field


@dataclass
class AuthConfig:
    """Authentication configuration.

    All settings can be overridden via environment variables (WAFT_AUTH_* prefix).
    When deployed via waft, these are injected automatically.
    """

    # Which providers are enabled (default: all available)
    providers: list[str] = field(
        default_factory=lambda: ["google", "apple", "password"]
    )

    # "open" = anyone can sign up; "invite_only" = admin must invite first
    signup_mode: str = "open"

    # Secrets — auto-loaded from env vars if not provided
    jwt_secret: str = ""
    auth_service_url: str = ""
    app_id: str = ""
    app_secret: str = ""

    # Route paths
    login_path: str = "/auth/login"
    register_path: str = "/auth/register"
    callback_path: str = "/auth/callback"
    logout_path: str = "/auth/logout"
    after_login_path: str = "/"
    after_logout_path: str = "/"

    # Cookie settings
    cookie_name: str = "waft_auth"
    cookie_max_age: int = 86400 * 30  # 30 days
    cookie_secure: bool = True

    # Test mode — enables X-Waft-Test-Auth header bypass
    test_mode: bool = False

    # Dev login — enables instant login with dev@waft.dev / dev
    # Auto-enabled when running locally (no WAFT_AUTH_APP_SECRET set)
    dev_login: bool = False

    def __post_init__(self) -> None:
        """Load settings from environment variables."""
        self.jwt_secret = (
            self.jwt_secret
            or os.environ.get("WAFT_AUTH_JWT_SECRET", "")
        )
        self.auth_service_url = (
            self.auth_service_url
            or os.environ.get("WAFT_AUTH_SERVICE_URL", "")
        )
        self.app_id = (
            self.app_id
            or os.environ.get("WAFT_AUTH_APP_ID", "")
        )
        self.app_secret = (
            self.app_secret
            or os.environ.get("WAFT_AUTH_APP_SECRET", "")
        )
        self.test_mode = (
            self.test_mode
            or os.environ.get("WAFT_AUTH_TEST_MODE", "").lower() == "true"
        )
        # Generate JWT secret if not provided (local dev)
        if not self.jwt_secret:
            self.jwt_secret = secrets.token_hex(32)
        # Auto-detect secure cookies
        if not self.auth_service_url or "localhost" in self.auth_service_url:
            self.cookie_secure = False
        # Auto-enable dev login when running locally (no app_secret = not deployed)
        if not self.app_secret and not self.dev_login:
            env_dev = os.environ.get("WAFT_AUTH_DEV_LOGIN", "")
            if env_dev.lower() == "false":
                self.dev_login = False
            else:
                self.dev_login = True
