import json
import logging
import requests
import numpy as np

class GenAIEmbedder:
    """An embedder that uses the Google Generative AI service via direct synchronous HTTP."""
    def __init__(self, model_name: str, api_key: str, dimension: int):
        self.model_name = model_name
        self.api_key = api_key
        self.dimension = dimension

    def embed_text(self, text: str) -> np.ndarray:
        """
        Generates an embedding by making a direct synchronous HTTP POST request
        to the Gemini Embedding API.
        """
        logging.debug("Calling GenAI for embedding...")
        if not self.api_key:
            raise ValueError("API key not set for GenAIEmbedder.")

        # Construct the API endpoint URL
        model_path = self.model_name
        if not model_path.startswith("models/"):
            model_path = f"models/{model_path}"

        api_url = f"https://generativelanguage.googleapis.com/v1beta/{model_path}:embedContent"

        # Build the request headers and payload
        headers = {
            'Content-Type': 'application/json',
            'x-goog-api-key': self.api_key
        }
        payload = {
            "model": model_path,
            "content": {"parts": [{"text": text}]},
            "output_dimensionality": self.dimension
        }

        try:
            # Use the synchronous 'requests' library
            response = requests.post(api_url, headers=headers, data=json.dumps(payload))
            response.raise_for_status() # Raise an exception for bad status codes

            result = response.json()
            
            # The 'embedding' field in the JSON response contains a 'values' list.
            if 'embedding' not in result or 'values' not in result['embedding']:
                raise KeyError("API response is missing the 'embedding' or 'values' field.")

            # Extract the embedding values and convert to a numpy array
            embedding = np.array(result["embedding"]["values"], dtype='float32').reshape(1, -1)
            logging.debug("GenAI embedding successfully generated.")
            return embedding
        except requests.exceptions.RequestException as e:
            logging.error(f"HTTP client error embedding text with GenAI: {e}")
            raise
        except Exception as e:
            logging.error(f"Error embedding text with GenAI: {e}")
            raise e
