"""Production config from environment."""

from __future__ import annotations

import os
from dataclasses import dataclass

ENV_IAT_MAX_AGE_MINUTES = "ECT_IAT_MAX_AGE_MINUTES"
ENV_IAT_MAX_FUTURE_SEC = "ECT_IAT_MAX_FUTURE_SEC"
ENV_DEFAULT_EXPIRY_MIN = "ECT_DEFAULT_EXPIRY_MIN"
ENV_JTI_REPLAY_CACHE_SIZE = "ECT_JTI_REPLAY_CACHE_SIZE"
ENV_JTI_REPLAY_TTL_MIN = "ECT_JTI_REPLAY_TTL_MIN"


@dataclass
class Config:
    iat_max_age_sec: int = 900
    iat_max_future_sec: int = 30
    default_expiry_sec: int = 600
    jti_replay_size: int = 0
    jti_replay_ttl_sec: int = 3600

    def create_options(self, key_id: str) -> "CreateOptions":
        from ect.create import CreateOptions
        return CreateOptions(
            key_id=key_id,
            default_expiry_sec=self.default_expiry_sec,
        )

    def verify_options(self) -> "VerifyOptions":
        from ect.verify import VerifyOptions
        from ect.dag import default_dag_config
        return VerifyOptions(
            iat_max_age_sec=self.iat_max_age_sec,
            iat_max_future_sec=self.iat_max_future_sec,
            dag=default_dag_config(),
        )


def default_config() -> Config:
    return Config()


def _int_env(name: str, default: int) -> int:
    v = os.environ.get(name)
    if v is None or v == "":
        return default
    try:
        return int(v)
    except ValueError:
        return default


def load_config_from_env() -> Config:
    c = default_config()
    c.iat_max_age_sec = _int_env(ENV_IAT_MAX_AGE_MINUTES, 15) * 60
    c.iat_max_future_sec = _int_env(ENV_IAT_MAX_FUTURE_SEC, 30)
    c.default_expiry_sec = _int_env(ENV_DEFAULT_EXPIRY_MIN, 10) * 60
    c.jti_replay_size = _int_env(ENV_JTI_REPLAY_CACHE_SIZE, 0)
    c.jti_replay_ttl_sec = _int_env(ENV_JTI_REPLAY_TTL_MIN, 60) * 60
    return c
