import json

import requests

from app.config import ollama_url, embedding_model_name, logger


def generate_embeddings(content):
    # Convert content to string if it's not already
    if not isinstance(content, str):
        try:
            content = json.dumps(content)
        except Exception as e:
            logger.error(
                f"Error converting content to string: {str(e)}. Defaulting to string.")
            content = str(content)

    logger.info(
        f"Generating embeddings for content: {content[:100]}...")  # Log first 100 chars
    try:
        response = requests.post(f"{ollama_url}/api/embed", json={
            "model": embedding_model_name,
            "input": content
        })
        response.raise_for_status()  # Raise an exception for bad status codes
        embeddings = response.json().get('embeddings')[0]
        if embeddings:
            logger.info(
                f"Successfully generated embeddings of length {len(embeddings)}")
            return embeddings
        else:
            raise ValueError("No embeddings found in response")
    except requests.RequestException as e:
        logger.error(f"Error making request to Ollama API: {str(e)}")
        logger.error(
            f"Response content: {e.response.text if e.response else 'No response'}")
        raise
    except json.JSONDecodeError:
        logger.error(f"Error decoding JSON response: {e.response.text}")
        raise
    except Exception as e:
        logger.error(f"Unexpected error generating embeddings: {str(e)}")
        raise
