from __future__ import annotations
from typing import Any, Optional
import json

def oa_messages_to_gemini(messages: list[dict]) -> tuple[Optional[dict], list[dict]]:
    system_texts: list[str] = []
    contents: list[dict] = []

    for m in messages:
        role = m.get("role")
        content = m.get("content", "")

        # 兼容 content 为 list（OpenAI 多模态结构），这里只取 text
        if isinstance(content, list):
            texts = []
            for part in content:
                if isinstance(part, dict) and part.get("type") == "text":
                    texts.append(part.get("text", ""))
            content = "\n".join([t for t in texts if t])

        content = "" if content is None else str(content)

        if role == "system":
            if content.strip():
                system_texts.append(content)
            continue

        g_role = "model" if role == "assistant" else "user"
        contents.append({"role": g_role, "parts": [{"text": content}]})

    system_instruction = None
    if system_texts:
        system_instruction = {"parts": [{"text": "\n".join(system_texts)}]}
    return system_instruction, contents

def gemini_text(resp_json: dict) -> str:
    cands = resp_json.get("candidates") or []
    if not cands:
        return ""
    content = (cands[0].get("content") or {})
    parts = content.get("parts") or []
    return "".join([p.get("text", "") for p in parts if isinstance(p, dict)])

def gemini_to_openai_like(resp_json: dict) -> dict:
    text = gemini_text(resp_json)
    return {
        "object": "chat.completion",
        "choices": [{
            "index": 0,
            "message": {"role": "assistant", "content": text},
            "finish_reason": "stop",
        }],
        "raw": resp_json,
    }

def build_gemini_payload(body: dict) -> dict:
    sys_inst, contents = oa_messages_to_gemini(body.get("messages") or [])
    payload: dict[str, Any] = {"contents": contents}

    if sys_inst:
        payload["systemInstruction"] = sys_inst

    gen_cfg = {}
    if "temperature" in body:
        gen_cfg["temperature"] = body["temperature"]
    if "max_tokens" in body:
        gen_cfg["maxOutputTokens"] = body["max_tokens"]
    if gen_cfg:
        payload["generationConfig"] = gen_cfg

    # 强制 JSON 输出（对“标签任务”非常有用）
    # 允许业务侧 body["response_mime_type"]="application/json"
    if body.get("response_mime_type"):
        payload["generationConfig"] = {**payload.get("generationConfig", {}), "responseMimeType": body["response_mime_type"]}

    return payload
