"""
Factory helpers: create IamClient from config or from environment.

Usage:
    client = create_iam_client(iam_base_url="...", client_id="...", client_secret="...")
    client = create_iam_client_from_env()
    config = resolve_iam_env_config();  # then pass to create_iam_client(**config)
"""
from __future__ import annotations

import os
from typing import Any

from .client import IamClient


def create_iam_client(
    *,
    iam_base_url: str,
    client_id: str,
    client_secret: str,
    app_token_cache_ttl_ms: int | None = None,
    permission_cache_ttl_ms: int | None = None,
    timeout_ms: int | None = None,
) -> IamClient:
    return IamClient(
        iam_base_url=iam_base_url,
        client_id=client_id,
        client_secret=client_secret,
        app_token_cache_ttl_ms=app_token_cache_ttl_ms,
        permission_cache_ttl_ms=permission_cache_ttl_ms,
        timeout_ms=timeout_ms,
    )


def resolve_iam_env_config(
    *,
    env: dict[str, str] | None = None,
    allow_legacy_nexa_env: bool = True,
    default_iam_base_url: str = "https://iamapi.easecation.net",
    default_iam_frontend_url: str = "https://iam.easecation.net",
) -> dict[str, Any]:
    e = env if env is not None else os.environ
    client_id = (e.get("IAM_CLIENT_ID") or (e.get("NEXA_APP_ID") if allow_legacy_nexa_env else "") or "")
    client_secret = (e.get("IAM_CLIENT_SECRET") or (e.get("NEXA_APP_SECRET") if allow_legacy_nexa_env else "") or "")

    raw_ttl = e.get("IAM_PERMISSION_CACHE_TTL", "300")
    try:
        permission_cache_ttl_seconds = int(raw_ttl)
    except ValueError:
        permission_cache_ttl_seconds = 300
    permission_cache_ttl_ms = permission_cache_ttl_seconds * 1000 if permission_cache_ttl_seconds > 0 else 300 * 1000

    return {
        "iam_base_url": e.get("IAM_BASE_URL") or default_iam_base_url,
        "iam_frontend_url": e.get("IAM_FRONTEND_URL") or default_iam_frontend_url,
        "client_id": client_id,
        "client_secret": client_secret,
        "permission_cache_ttl_ms": permission_cache_ttl_ms,
    }


def create_iam_client_from_env(
    *,
    env: dict[str, str] | None = None,
    allow_legacy_nexa_env: bool = True,
    default_iam_base_url: str = "https://iamapi.easecation.net",
    default_iam_frontend_url: str = "https://iam.easecation.net",
) -> IamClient:
    resolved = resolve_iam_env_config(
        env=env,
        allow_legacy_nexa_env=allow_legacy_nexa_env,
        default_iam_base_url=default_iam_base_url,
        default_iam_frontend_url=default_iam_frontend_url,
    )
    return create_iam_client(
        iam_base_url=resolved["iam_base_url"],
        client_id=resolved["client_id"],
        client_secret=resolved["client_secret"],
        permission_cache_ttl_ms=resolved["permission_cache_ttl_ms"],
    )
