import asyncio
from openai import AsyncOpenAI

async def embed(client: AsyncOpenAI, texts: list[str], model: str = "text-embedding-3-small") -> list[list[float]]:
    """
    Embed a list of texts using OpenAI.
    Truncates each text to 8000 chars.
    Retries 3x with exponential backoff on rate limit errors.
    """
    truncated = [t[:8000] for t in texts]

    for attempt in range(3):
        try:
            response = await client.embeddings.create(
                model=model,
                input=truncated,
            )
            return [item.embedding for item in response.data]
        except Exception as e:
            if "rate_limit" in str(e).lower() and attempt < 2:
                wait = 2 ** (attempt + 1)  # 2s, 4s, 8s
                await asyncio.sleep(wait)
                continue
            raise

    raise RuntimeError("Failed to embed after 3 retries")
