from __future__ import annotations

from typing import Any, Mapping

from ..config import (
    CLAIM_GROUPS,
    ROLE_ADMIN,
    ROLE_TRADER,
    ROLE_VIEWER,
    CognitoAuthConfig,
)

ROLE_PRIORITY = (ROLE_ADMIN, ROLE_TRADER, ROLE_VIEWER)

def _groups_from_claims(claims: Mapping[str, Any]) -> list[str]:
    raw_groups = claims.get(CLAIM_GROUPS)
    if not raw_groups:
        return []
    if isinstance(raw_groups, str):
        return [raw_groups]
    if isinstance(raw_groups, list):
        return [str(x) for x in raw_groups]
    return []

def resolve_role_from_claims(
    claims: Mapping[str, Any],
    config: CognitoAuthConfig,
) -> str | None:
    mapped: list[str] = []
    for group in _groups_from_claims(claims):
        if group in config.group_to_role:
            mapped.append(config.group_to_role[group])
            continue
        low = group.strip().lower()
        if low in (ROLE_ADMIN, ROLE_TRADER, ROLE_VIEWER):
            mapped.append(low)

    for role in ROLE_PRIORITY:
        if role in mapped:
            return role
    return None

class RoleMapper:
    def __init__(self, config: CognitoAuthConfig) -> None:
        self._config = config

    def map_role(self, claims: Mapping[str, Any]) -> str | None:
        return resolve_role_from_claims(claims, self._config)
        