from __future__ import annotations
from typing import Any
import dashscope
from dashscope.common.error import (
 AuthenticationError,
 InvalidParameter,
 RequestFailure,
 ServiceUnavailableError,
 TimeoutException,
)
from src.result_types import ErrorInfo, ErrorKind

def build_dashscope_tools(openai_tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
 out: list[dict[str, Any]] = []
 for t in openai_tools:
  if t.get("type") != "function":
   continue
  fn = t.get("function", {})
  out.append({
   "name": fn.get("name", ""),
   "description": fn.get("description", ""),
   "parameters": fn.get("parameters", {"type": "object", "properties": {}}),
  })
 return out

def classify_dashscope_error(exc: Exception, source: str = "qwen_adapter") -> ErrorInfo:
 if isinstance(exc, AuthenticationError):
  return ErrorInfo(kind=ErrorKind.AUTH, message=str(exc), source=source, original=exc)
 if isinstance(exc, TimeoutException):
  return ErrorInfo(kind=ErrorKind.NETWORK, message=str(exc), source=source, original=exc)
 if isinstance(exc, ServiceUnavailableError):
  return ErrorInfo(kind=ErrorKind.NETWORK, message=str(exc), source=source, original=exc)
 if isinstance(exc, InvalidParameter):
  return ErrorInfo(kind=ErrorKind.QUOTA, message=str(exc), source=source, original=exc)
 if isinstance(exc, RequestFailure):
  return ErrorInfo(kind=ErrorKind.NETWORK, message=str(exc), source=source, original=exc)
 return ErrorInfo(kind=ErrorKind.UNKNOWN, message=str(exc), source=source, original=exc)
