from __future__ import annotations

import logging
from typing import Any

from niannian.storage.cloud_auth.network_errors import is_transient_network_error
from niannian.storage.cloud_auth.onedrive_oauth import OneDriveOAuthError, apply_token_response, refresh_access_token
from niannian.storage.manifest import utc_now_iso

logger = logging.getLogger(__name__)


def refresh_onedrive(entry: dict[str, Any], *, config: dict[str, Any] | None = None) -> dict[str, Any]:
    refresh = entry.get("refresh_token")
    if not refresh:
        entry["status"] = "needs_relogin"
        entry["error"] = "missing_refresh_token"
        return entry
    try:
        token_data = refresh_access_token(str(refresh), config)
        return apply_token_response(entry, token_data)
    except OneDriveOAuthError as exc:
        logger.warning("onedrive oauth refresh failed: %s", exc)
        if is_transient_network_error(exc):
            entry["status"] = "degraded"
            entry["refresh_deferred"] = True
        else:
            entry["status"] = "needs_relogin"
        entry["error"] = str(exc)[:200]
        entry["updated_at"] = utc_now_iso()
        return entry
