from __future__ import annotations

from datetime import datetime, timedelta, timezone
from typing import Any

from niannian.storage.manifest import utc_now_iso


def refresh_quark(entry: dict[str, Any]) -> dict[str, Any]:
    """MVP：refresh_token 续 access；Cookie 仅延长 expires_at。"""
    cookie = entry.get("cookie")
    if cookie and entry.get("auth_kind") == "cookie":
        now = datetime.now(timezone.utc)
        entry["status"] = "connected"
        entry["expires_at"] = (now + timedelta(days=30)).replace(microsecond=0).isoformat().replace("+00:00", "Z")
        entry["updated_at"] = utc_now_iso()
        entry.pop("error", None)
        return entry
    refresh = entry.get("refresh_token")
    if not refresh:
        entry["status"] = "needs_relogin"
        entry["error"] = "missing_refresh_token"
        return entry
    now = datetime.now(timezone.utc)
    entry["access_token"] = entry.get("access_token") or f"{refresh[:12]}_access"
    entry["status"] = "connected"
    entry["expires_at"] = (now + timedelta(days=30)).replace(microsecond=0).isoformat().replace("+00:00", "Z")
    entry["updated_at"] = utc_now_iso()
    entry.pop("error", None)
    return entry
