from __future__ import annotations

import os
from typing import Any

from niannian.storage.manifest import utc_now_iso

_ENV_MAP = {
    "quark": ("QUARK_REFRESH_TOKEN", "refresh_token"),
    "baidu": ("BAIDU_REFRESH_TOKEN", "refresh_token"),
    "feimao": ("FEIMAO_SESSION_TOKEN", "session_token"),
}


def import_legacy_providers(vault: dict[str, Any], providers: dict[str, Any] | None) -> int:
    """从 providers.local / env 一次性导入 token。"""
    imported = 0
    providers = providers or {}

    quark = providers.get("quark") or {}
    quark_entry = vault.setdefault("quark", {})
    if not (quark_entry.get("status") == "connected" and (quark_entry.get("cookie") or quark_entry.get("refresh_token"))):
        cookie = quark.get("cookie") or os.environ.get("QUARK_COOKIE")
        if cookie:
            quark_entry["cookie"] = cookie
            quark_entry["auth_kind"] = "cookie"
            quark_entry["status"] = "connected"
            quark_entry["updated_at"] = utc_now_iso()
            quark_entry.pop("error", None)
            imported += 1

    for name, (env_key, field) in _ENV_MAP.items():
        entry = vault.setdefault(name, {})
        if entry.get("status") == "connected" and entry.get(field):
            continue
        prov = providers.get(name) or {}
        token = prov.get(field) or prov.get("refresh_token") or prov.get("access_token")
        if not token:
            token = os.environ.get(env_key)
        if not token:
            continue
        entry[field] = token
        if name in ("quark", "baidu") and field == "refresh_token":
            entry.setdefault("access_token", f"{str(token)[:12]}_access")
        entry["status"] = "connected"
        entry["updated_at"] = utc_now_iso()
        entry.pop("error", None)
        imported += 1
    return imported
