"""Parse pasted AI response into scaffold fields. Tolerant of fenced/freeform output."""
import json
import re


def _strip_fences(text):
    text = text.strip()
    m = re.match(r'^```(?:json)?\s*(.*?)\s*```$', text, re.DOTALL)
    if m:
        return m.group(1).strip()
    return text


def _try_json(text):
    text = _strip_fences(text)
    try:
        return json.loads(text)
    except Exception:
        pass
    start = text.find('{')
    end = text.rfind('}')
    if start >= 0 and end > start:
        try:
            return json.loads(text[start:end + 1])
        except Exception:
            pass
    return None


def parse_response(raw):
    """Return {'roman_urdu_intro': str, 'vocabulary_bridge': dict, 'socratic_hints_ur': list}."""
    if not raw or not raw.strip():
        raise ValueError('Empty response')

    data = _try_json(raw)
    if isinstance(data, dict):
        intro = data.get('roman_urdu_intro') or data.get('intro') or ''
        result_intro = str(intro).strip()

        vocab_raw = data.get('vocabulary_bridge') or data.get('vocab') or {}
        if isinstance(vocab_raw, dict):
            vocab = {str(k): str(v) for k, v in vocab_raw.items() if k and v is not None}
        elif isinstance(vocab_raw, list):
            vocab = {}
            for item in vocab_raw:
                if isinstance(item, dict):
                    k = item.get('english') or item.get('term') or item.get('en')
                    v = item.get('roman_urdu') or item.get('translation') or item.get('ur')
                    if k and v:
                        vocab[str(k)] = str(v)
        else:
            vocab = {}

        hints_raw = data.get('socratic_hints_ur') or data.get('hints') or []
        if isinstance(hints_raw, list):
            hints = [str(h).strip() for h in hints_raw if str(h).strip()]
        else:
            hints = []

        return {
            'roman_urdu_intro': result_intro[:4000],
            'vocabulary_bridge': vocab,
            'socratic_hints_ur': hints[:10],
        }

    # Fallback: entire text as intro
    return {
        'roman_urdu_intro': raw.strip()[:4000],
        'vocabulary_bridge': {},
        'socratic_hints_ur': [],
    }
