from __future__ import annotations

from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional

from pydantic_settings import BaseSettings

from keiro.gateway.infra.settings import get_gateway_settings as get_legacy_gateway_settings


@dataclass
class StoreSettings:
    postgres_dsn: Optional[str] = None
    redis_url: Optional[str] = None
    auto_init: bool = False


@dataclass
class LimitSettings:
    default_tpm: Optional[int] = None


@dataclass
class ConfigPaths:
    tiers_path: str = str(Path.home() / ".ember" / "tiers.yaml")


@dataclass
class LoggingSettings:
    enabled: bool = True
    path: Optional[str] = None
    level: str = "INFO"


@dataclass
class AuthSettings:
    mode: str = "memory"
    require_auth: bool = False
    issued_keys: list[str] = field(default_factory=lambda: ["dev-key:org_dev"])
    default_tier: str = "T1"
    dev_default_tier: str = "T3"
    pepper: str = ""
    key_prefix: str = "tkm_sk"


class GatewaySettings(BaseSettings):
    """Gateway configuration settings.

    Reads from the primary gateway settings loader.
    """

    default_tier: str = "T1"
    sur_dir: str = "tmp/sur"
    postgres_dsn: Optional[str] = None
    redis_url: Optional[str] = None
    auto_init: bool = False
    default_tpm: Optional[int] = None
    tiers_path: str = str(Path.home() / ".ember" / "tiers.yaml")
    logging_enabled: bool = True
    logging_path: Optional[str] = None
    logging_level: str = "INFO"
    # Auth settings
    auth_mode: str = "memory"
    auth_require_auth: bool = False
    auth_issued_keys: str = "dev-key:org_dev"
    auth_default_tier: str = "T1"
    auth_dev_default_tier: str = "T3"
    auth_pepper: str = ""
    auth_key_prefix: str = "tkm_sk"

    class Config:
        env_prefix = "EMBER_GATEWAY2_"

    @property
    def stores(self) -> StoreSettings:
        """Return store settings (for compatibility with gateway1 middleware)."""
        return StoreSettings(
            postgres_dsn=self.postgres_dsn,
            redis_url=self.redis_url,
            auto_init=self.auto_init,
        )

    def limits(self) -> LimitSettings:
        """Return limit settings."""
        return LimitSettings(default_tpm=self.default_tpm)

    @property
    def config(self) -> ConfigPaths:
        """Return config paths as attribute (for compatibility with gateway1 middleware)."""
        return ConfigPaths(tiers_path=self.tiers_path)

    def logging(self) -> LoggingSettings:
        """Return logging settings."""
        return LoggingSettings(
            enabled=self.logging_enabled,
            path=self.logging_path,
            level=self.logging_level,
        )

    @property
    def auth(self) -> AuthSettings:
        """Return auth settings (for compatibility with gateway1 middleware)."""
        # Parse issued_keys from comma-separated string
        issued_keys = [k.strip() for k in self.auth_issued_keys.split(",") if k.strip()]
        return AuthSettings(
            mode=self.auth_mode,
            require_auth=self.auth_require_auth,
            issued_keys=issued_keys,
            default_tier=self.auth_default_tier,
            dev_default_tier=self.auth_dev_default_tier,
            pepper=self.auth_pepper,
            key_prefix=self.auth_key_prefix,
        )

def get_gateway_settings() -> GatewaySettings:
    legacy = get_legacy_gateway_settings()
    issued_keys = ",".join(legacy.auth.issued_keys)
    return GatewaySettings(
        default_tier=legacy.auth.default_tier,
        sur_dir=legacy.admin.sur_dir,
        postgres_dsn=legacy.stores.postgres_dsn,
        redis_url=legacy.stores.redis_url,
        auto_init=legacy.stores.auto_init,
        default_tpm=legacy.limits.default_tpm,
        tiers_path=legacy.config.tiers_path,
        logging_enabled=legacy.logging.enabled,
        logging_path=legacy.logging.path,
        logging_level=legacy.logging.level,
        auth_mode=legacy.auth.mode,
        auth_require_auth=legacy.auth.require_auth,
        auth_issued_keys=issued_keys,
        auth_default_tier=legacy.auth.default_tier,
        auth_dev_default_tier=legacy.auth.dev_default_tier,
        auth_pepper=legacy.auth.pepper,
        auth_key_prefix=legacy.auth.key_prefix,
    )
