"""Shared Gemini JSON call for extraction and merge: thinking budget and output-token accounting."""

import logging
from typing import Any, Dict, Optional

from google.genai import types

from .. import config

logger = logging.getLogger("ocr.gemini_json")

# Models that rejected an explicit thinking config; later calls to them omit it.
_thinking_unsupported: set = set()


def _build_config(system_instruction: str, temperature: float, with_thinking: bool,
                  response_schema: Optional[Dict[str, Any]] = None) -> types.GenerateContentConfig:
    kwargs: Dict[str, Any] = {
        "system_instruction": system_instruction,
        "response_mime_type": "application/json",
        "temperature": temperature,
    }
    if response_schema is not None:
        kwargs["response_schema"] = response_schema
    if with_thinking:
        kwargs["thinking_config"] = types.ThinkingConfig(thinking_budget=config.GEMINI_THINKING_BUDGET)
    return types.GenerateContentConfig(**kwargs)


def generate_json(client, model_name: str, prompt: str, system_instruction: str, temperature: float = 0.1,
                  response_schema: Optional[Dict[str, Any]] = None):
    """
    Calls generate_content in JSON mode with the configured thinking budget. With response_schema
    (Gemini structured output) the answer is guaranteed to be valid JSON matching the schema.
    If a request with a thinking config is rejected as invalid (the API may answer a bare
    "400 INVALID_ARGUMENT" without naming the field), retries once without it and remembers that
    for the model. Other errors propagate to the caller's retry logic.
    """
    with_thinking = config.GEMINI_THINKING_BUDGET is not None and model_name not in _thinking_unsupported
    try:
        return client.models.generate_content(
            model=model_name,
            contents=prompt,
            config=_build_config(system_instruction, temperature, with_thinking, response_schema),
        )
    except Exception as e:
        msg = str(e).lower()
        if not with_thinking or not ("thinking" in msg or "invalid_argument" in msg):
            raise
        logger.warning("Model %s rejected thinking_budget=%s; retrying without a thinking config",
                       model_name, config.GEMINI_THINKING_BUDGET)
        _thinking_unsupported.add(model_name)
        return client.models.generate_content(
            model=model_name,
            contents=prompt,
            config=_build_config(system_instruction, temperature, False, response_schema),
        )


def usage_tokens(response) -> Dict[str, int]:
    """
    Token usage of a response. candidates_tokens includes thought tokens, because both are billed
    as output; thoughts_tokens is reported separately as well.
    """
    usage: Optional[Any] = getattr(response, "usage_metadata", None)
    if not usage:
        return {"prompt_tokens": 0, "candidates_tokens": 0, "thoughts_tokens": 0, "total_tokens": 0}
    prompt = getattr(usage, "prompt_token_count", 0) or 0
    cand = getattr(usage, "candidates_token_count", 0) or 0
    thoughts = getattr(usage, "thoughts_token_count", 0) or 0
    total = getattr(usage, "total_token_count", 0) or (prompt + cand + thoughts)
    return {
        "prompt_tokens": prompt,
        "candidates_tokens": cand + thoughts,
        "thoughts_tokens": thoughts,
        "total_tokens": total,
    }


def response_text(response) -> str:
    """Text of a response, falling back to concatenated candidate parts."""
    text = getattr(response, "text", None) or ""
    if not text:
        for cand in getattr(response, "candidates", None) or []:
            content = getattr(cand, "content", None)
            for part in getattr(content, "parts", None) or []:
                if getattr(part, "text", None):
                    text += part.text
    return text.strip()
