# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from .. import core
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..errors.not_found_error import NotFoundError
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.image_analyze_response import ImageAnalyzeResponse

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawVisionClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def analyze_image(
        self,
        *,
        image_file: core.File,
        schema: str,
        organization_id: str,
        prompt: typing.Optional[str] = OMIT,
        model: typing.Optional[str] = OMIT,
        provider: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ImageAnalyzeResponse]:
        """
        Analyze image and extract structured data using OpenAI Vision API.

            **Supported Providers:**
            - `openai`: GPT-5 Vision API (Aug 2025+)

            **Parameters:**
            - `image_file`: Image to analyze (PNG, JPEG, WebP)
            - `schema`: JSON schema defining extraction structure
            - `organization_id`: Organization ID (org_ prefixed string)
            - `prompt`: Optional custom instructions (e.g., "Focus on text in the center", "Ignore watermarks")
            - `model`: GPT-5 model to use (gpt-5 standard, gpt-5.1 latest, gpt-5-turbo fast, gpt-5-mini cost-effective)
            - `provider`: Provider to use (currently only openai)

            **Model Selection (GPT-5 Series Only):**
            - `gpt-5`: Standard model - best balance of quality and speed (~$0.03 per image)
            - `gpt-5.1`: Latest iteration (Nov 2025) - faster, customizable personalities (~$0.03 per image)
            - `gpt-5-turbo`: Optimized for speed while maintaining quality (~$0.02 per image)
            - `gpt-5-mini`: Fast and cost-effective for simple tasks (~$0.01 per image)

            **Use Cases:**
            - Extract data from photos
            - Analyze screenshots
            - Process scanned documents
            - OCR with structured output
            - Invoice/receipt processing

            **Billing:**
            - Cost: ~$0.01-0.03 per image (depends on GPT-5 variant)
            - Tracked through usage_events system

            **Response Headers:**
            - `X-Provider`: Provider that processed the request
            - `X-Model-Used`: Actual model used
            - `X-Cost-CHF`: Total cost in CHF

        Parameters
        ----------
        image_file : core.File
            See core.File for more documentation

        schema : str
            JSON schema defining extraction structure

        organization_id : str
            Organization ID (org_ prefixed string)

        prompt : typing.Optional[str]
            Optional custom instructions for analysis

        model : typing.Optional[str]
            GPT-5 model to use (gpt-5 standard, gpt-5.1 latest, gpt-5-turbo fast, gpt-5-mini cost-effective)

        provider : typing.Optional[str]
            Provider to use (currently only openai)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ImageAnalyzeResponse]
            Image analyzed successfully
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/vision/analyze-image",
            method="POST",
            data={
                "schema": schema,
                "organization_id": organization_id,
                "prompt": prompt,
                "model": model,
                "provider": provider,
            },
            files={
                "image_file": image_file,
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ImageAnalyzeResponse,
                    parse_obj_as(
                        type_=ImageAnalyzeResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawVisionClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def analyze_image(
        self,
        *,
        image_file: core.File,
        schema: str,
        organization_id: str,
        prompt: typing.Optional[str] = OMIT,
        model: typing.Optional[str] = OMIT,
        provider: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ImageAnalyzeResponse]:
        """
        Analyze image and extract structured data using OpenAI Vision API.

            **Supported Providers:**
            - `openai`: GPT-5 Vision API (Aug 2025+)

            **Parameters:**
            - `image_file`: Image to analyze (PNG, JPEG, WebP)
            - `schema`: JSON schema defining extraction structure
            - `organization_id`: Organization ID (org_ prefixed string)
            - `prompt`: Optional custom instructions (e.g., "Focus on text in the center", "Ignore watermarks")
            - `model`: GPT-5 model to use (gpt-5 standard, gpt-5.1 latest, gpt-5-turbo fast, gpt-5-mini cost-effective)
            - `provider`: Provider to use (currently only openai)

            **Model Selection (GPT-5 Series Only):**
            - `gpt-5`: Standard model - best balance of quality and speed (~$0.03 per image)
            - `gpt-5.1`: Latest iteration (Nov 2025) - faster, customizable personalities (~$0.03 per image)
            - `gpt-5-turbo`: Optimized for speed while maintaining quality (~$0.02 per image)
            - `gpt-5-mini`: Fast and cost-effective for simple tasks (~$0.01 per image)

            **Use Cases:**
            - Extract data from photos
            - Analyze screenshots
            - Process scanned documents
            - OCR with structured output
            - Invoice/receipt processing

            **Billing:**
            - Cost: ~$0.01-0.03 per image (depends on GPT-5 variant)
            - Tracked through usage_events system

            **Response Headers:**
            - `X-Provider`: Provider that processed the request
            - `X-Model-Used`: Actual model used
            - `X-Cost-CHF`: Total cost in CHF

        Parameters
        ----------
        image_file : core.File
            See core.File for more documentation

        schema : str
            JSON schema defining extraction structure

        organization_id : str
            Organization ID (org_ prefixed string)

        prompt : typing.Optional[str]
            Optional custom instructions for analysis

        model : typing.Optional[str]
            GPT-5 model to use (gpt-5 standard, gpt-5.1 latest, gpt-5-turbo fast, gpt-5-mini cost-effective)

        provider : typing.Optional[str]
            Provider to use (currently only openai)

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ImageAnalyzeResponse]
            Image analyzed successfully
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/vision/analyze-image",
            method="POST",
            data={
                "schema": schema,
                "organization_id": organization_id,
                "prompt": prompt,
                "model": model,
                "provider": provider,
            },
            files={
                "image_file": image_file,
            },
            request_options=request_options,
            omit=OMIT,
            force_multipart=True,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ImageAnalyzeResponse,
                    parse_obj_as(
                        type_=ImageAnalyzeResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 404:
                raise NotFoundError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        parse_obj_as(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
