import json
import numpy as np
from openai import AsyncOpenAI

async def label_holes(
    client: AsyncOpenAI,
    holes: list[dict],
    embeddings: np.ndarray,
    metadata: list[dict],
    model: str = "gpt-4o-mini",
    generate_suggestions: bool = True,
) -> list[dict]:
    """
    For each detected hole, use nearby document context to generate:
    - topic_label: short descriptive name for the gap
    - explanation: why this topic is missing
    - suggested_content: what to write to fill the gap (optional)
    """
    labeled = []

    for rank, hole in enumerate(holes):
        nearby_indices = hole.get("nearby_indices", [])
        centroid_idx = hole.get("centroid_idx", 0)

        # Gather context from nearby documents
        context_docs = []
        for idx in [centroid_idx] + nearby_indices:
            if 0 <= idx < len(metadata):
                context_docs.append(metadata[idx].get("content", ""))

        context_text = "\n---\n".join(context_docs[:3])

        prompt = f"""You are analyzing a document for content gaps using Topological Data Analysis.

A "hole" was detected in the semantic embedding space near these text segments:

{context_text}

This hole has persistence {hole['persistence']:.3f} (higher = more significant gap).

Respond in JSON with these fields:
- "topic_label": A short (3-6 word) label for what topic is MISSING
- "explanation": 1-2 sentences explaining what content gap this represents
{"- \"suggested_content\": 2-3 sentences of content that would fill this gap" if generate_suggestions else ""}

Respond ONLY with valid JSON, no markdown."""

        try:
            response = await client.chat.completions.create(
                model=model,
                messages=[{"role": "user", "content": prompt}],
                response_format={"type": "json_object"},
                temperature=0.7,
                max_tokens=500,
            )

            result = json.loads(response.choices[0].message.content)

            labeled.append({
                "topic_label": result.get("topic_label", f"Gap #{rank + 1}"),
                "explanation": result.get("explanation", "A content gap was detected in this area."),
                "suggested_content": result.get("suggested_content") if generate_suggestions else None,
                "persistence": hole["persistence"],
                "rank": rank + 1,
            })

        except Exception:
            # On parse failure, return generic label — do not crash
            labeled.append({
                "topic_label": f"Content Gap #{rank + 1}",
                "explanation": f"A semantic gap with persistence {hole['persistence']:.3f} was detected near existing content.",
                "suggested_content": None,
                "persistence": hole["persistence"],
                "rank": rank + 1,
            })

    return labeled
