from __future__ import annotations

import logging
from typing import Any

logger = logging.getLogger(__name__)

DEFAULT_TIER_CHAIN = ("quark", "baidu", "onedrive")


def resolve_tier_chain(tier_cfg: dict[str, Any] | None = None) -> tuple[str, ...]:
    """Resolve daily tier chain from config; filter disabled / deprecated providers."""
    tier_cfg = tier_cfg or {}
    raw = tier_cfg.get("chain") or list(DEFAULT_TIER_CHAIN)
    chain: list[str] = []
    for name in raw:
        provider = str(name).strip().lower()
        if not provider:
            continue
        if provider == "feimao":
            feimao_cfg = tier_cfg.get("feimao") or {}
            role = str(feimao_cfg.get("role") or "").lower()
            if role == "disabled" or not feimao_cfg.get("failover_enabled", True):
                logger.warning("tier chain: feimao deprecated in v0.2.9 — skipping from active chain")
                continue
            logger.warning("tier chain: feimao in chain is deprecated — prefer onedrive")
        chain.append(provider)
    if not chain:
        return DEFAULT_TIER_CHAIN
    return tuple(chain)


def role_for_provider(provider: str) -> str:
    if provider == "quark":
        return "quark"
    return f"{provider}_failover"


def provider_for_role(role: str) -> str:
    if role == "local_degraded":
        return "local"
    if role == "quark":
        return "quark"
    if role.endswith("_failover"):
        return role[: -len("_failover")]
    return "quark"


def build_role_map(chain: tuple[str, ...]) -> dict[str, str]:
    return {name: role_for_provider(name) for name in chain}


def is_feimao_disabled(tier_cfg: dict[str, Any] | None = None) -> bool:
    tier_cfg = tier_cfg or {}
    feimao_cfg = tier_cfg.get("feimao") or {}
    role = str(feimao_cfg.get("role") or "").lower()
    return role == "disabled" or not feimao_cfg.get("live", True)
