"""Map google-genai exceptions and responses to one internal outcome: layer, kind, retryable."""
from __future__ import annotations

import json
from dataclasses import dataclass

from google.genai import errors, types

RETRYABLE_CODES = {408, 429, 500, 502, 503, 504}
POLICY_STOPS = {"SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII"}


@dataclass(frozen=True)
class Outcome:
    layer: str      # "platform", "response" or "service"
    kind: str
    retryable: bool


def from_exception(exc: Exception) -> Outcome:
    if isinstance(exc, errors.APIError):  # ClientError (4xx) and ServerError (5xx) both land here
        return Outcome("platform", f"http_{exc.code}_{exc.status}", exc.code in RETRYABLE_CODES)
    if isinstance(exc, TimeoutError):
        return Outcome("service", "deadline", False)
    return Outcome("service", type(exc).__name__, False)


def from_response(resp: types.GenerateContentResponse, required: tuple[str, ...]) -> Outcome:
    if resp.prompt_feedback and resp.prompt_feedback.block_reason:
        return Outcome("response", f"prompt_blocked_{resp.prompt_feedback.block_reason.name}", False)
    if not resp.candidates:
        return Outcome("response", "no_candidates", True)
    reason = resp.candidates[0].finish_reason
    if reason is not None and reason.name == "MAX_TOKENS":
        return Outcome("response", "truncated", False)  # raise max_output_tokens or shorten the task
    if reason is not None and reason.name in POLICY_STOPS:
        return Outcome("response", f"stopped_{reason.name}", False)
    try:
        data = json.loads(resp.text or "")
    except json.JSONDecodeError:
        return Outcome("response", "invalid_json", True)
    if any(k not in data for k in required):
        return Outcome("response", "schema_mismatch", True)
    return Outcome("response", "ok", False)


def fake_response(text: str, finish: str = "STOP", blocked: str | None = None) -> types.GenerateContentResponse:
    feedback = types.GenerateContentResponsePromptFeedback(block_reason=blocked) if blocked else None
    candidate = types.Candidate(content=types.Content(role="model", parts=[types.Part(text=text)]),
                                finish_reason=finish)
    return types.GenerateContentResponse(candidates=[] if blocked else [candidate], prompt_feedback=feedback)


if __name__ == "__main__":
    def api_error(cls, code: int, status: str) -> errors.APIError:
        return cls(code, {"error": {"code": code, "message": "...", "status": status}})

    cases = {
        "HTTP 429": api_error(errors.ClientError, 429, "RESOURCE_EXHAUSTED"),
        "HTTP 400": api_error(errors.ClientError, 400, "INVALID_ARGUMENT"),
        "HTTP 503": api_error(errors.ServerError, 503, "UNAVAILABLE"),
        "deadline": TimeoutError(),
    }
    for label, exc in cases.items():
        print(f"{label:22s} {from_exception(exc)}")
    responses = {
        "valid JSON": fake_response('{"title": "A", "items": 2}'),
        "cut at max tokens": fake_response('{"title": "A", "ite', finish="MAX_TOKENS"),
        "safety stop": fake_response("", finish="SAFETY"),
        "prompt blocked": fake_response("", blocked="PROHIBITED_CONTENT"),
        "missing key": fake_response('{"title": "A"}'),
    }
    for label, resp in responses.items():
        print(f"{label:22s} {from_response(resp, required=('title', 'items'))}")
