from __future__ import annotations
from typing import List
from ..config import settings
from ..models.core import SemanticAtom

ENRICH_SYSTEM = (
    "You are an assistant that augments short educational atoms. "
    "Return a concise JSON object with keys: summary (<=40 words), difficulty (1-5), questions (array of up to 2 short formative questions)."
)

def _build_prompt(atom: SemanticAtom) -> str:
    return (
        f"{ENRICH_SYSTEM}\nText: {atom.text}\nKind: {atom.kind}\nRespond JSON only."
    )

def enrich_atoms(atoms: List[SemanticAtom], limit: int = 10) -> List[dict]:
    if not settings.llm_enabled:
        return []
    # Import here so monkeypatching granule.llm.base.get_provider in tests works reliably
    from . import base as llm_base  # local import
    provider = llm_base.get_provider(settings.llm_provider)
    if not provider:
        return []
    enriched: List[dict] = []
    for atom in atoms[:limit]:
        prompt = _build_prompt(atom)
        from .base import LLMRequest  # local to avoid circular during tests
        resp = provider.complete(LLMRequest(prompt=prompt))
        text = resp.text or ""
        # Minimal guard: ensure a JSON-looking string so downstream parser attempts succeed later
        if text and not text.lstrip().startswith("{"):
            text = '{"summary": ' + repr(text[:40]) + ', "difficulty": 3, "questions": []}'
        data = {"atom_id": str(atom.id), "raw": text}
        enriched.append(data)
    return enriched
