"""config.yaml 版本迁移：每次结构变更递增 ``CURRENT_CONFIG_VERSION``，并增加一级 ``migrate_vN_to_vN+1``。"""

from __future__ import annotations

from typing import Any

# 与磁盘 ``configVersion`` 对齐；修改配置结构时请 +1 并实现对应 migrate 函数
CURRENT_CONFIG_VERSION = 1


def migrate_v0_to_v1(data: dict[str, Any]) -> dict[str, Any]:
    """
    v0：无 ``configVersion``、无 ``llmProfiles``，仅顶层 ``llm``。
    v1：增加 ``llmProfiles``、``activeLlmProfile``、``configVersion``。
    """
    d = dict(data)
    lp = d.get("llmProfiles") or d.get("llm_profiles")
    if isinstance(lp, list) and len(lp) > 0:
        if not d.get("activeLlmProfile") and not d.get("active_llm_profile"):
            first = lp[0]
            if isinstance(first, dict) and first.get("name"):
                d["activeLlmProfile"] = str(first["name"])
            else:
                d["activeLlmProfile"] = "default"
        return d

    llm = d.get("llm") if isinstance(d.get("llm"), dict) else {}
    proto = str(llm.get("proto") or "openai").strip()
    prof: dict[str, Any] = {
        "name": "default",
        "proto": proto,
        "baseUrl": str(llm.get("baseUrl") or llm.get("base_url") or "").strip(),
        "apiKey": str(llm.get("apiKey") or llm.get("api_key") or "").strip(),
        "modelId": str(llm.get("modelId") or llm.get("model") or "gpt-4o-mini").strip(),
    }
    vm = llm.get("visionModel") or llm.get("vision_model")
    if vm not in (None, ""):
        prof["visionModel"] = str(vm).strip()
    mct = llm.get("modelContextTokens") or llm.get("model_context_tokens")
    if isinstance(mct, dict) and mct:
        mid = prof["modelId"]
        raw_ctx = (
            mct.get(mid)
            or mct.get(mid.lower())
            or mct.get("default")
            or mct.get("*")
        )
        if raw_ctx is not None and str(raw_ctx).strip() != "":
            try:
                iv = int(raw_ctx)
                if iv > 0:
                    prof["contextWindowTokens"] = iv
            except (TypeError, ValueError):
                pass
    d["llmProfiles"] = [prof]
    d["activeLlmProfile"] = str(prof["name"])
    return d


def migrate_config_dict(data: dict[str, Any]) -> dict[str, Any]:
    """将任意版本 YAML 字典升级到 ``CURRENT_CONFIG_VERSION``。"""
    if not isinstance(data, dict):
        data = {}
    ver = int(data.get("configVersion") or data.get("config_version") or 0)
    d = dict(data)
    if ver < 1:
        d = migrate_v0_to_v1(d)
        ver = 1
    # if ver < 2:
    #     d = migrate_v1_to_v2(d)
    #     ver = 2
    d["configVersion"] = CURRENT_CONFIG_VERSION
    return d
