import logging
logger = logging.getLogger(__name__)
# Robust parsing for DeepSeek grading output.
import json
import json_repair
import re
from decimal import Decimal, InvalidOperation

_FENCE_RE = re.compile(r"```(?:json|JSON)?\s*\n?(.*?)\n?```", re.DOTALL)




def _repair_truncated_json(text):
    """Auto-close strings and brackets if AI truncated the response."""
    in_string = False
    escape = False
    for char in text:
        if in_string:
            if escape:
                escape = False
            elif char == '\\':
                escape = True
            elif char == '"':
                in_string = False
        else:
            if char == '"':
                in_string = True
                
    if in_string:
        text += '"'

    open_brackets = text.count('[')
    close_brackets = text.count(']')
    open_braces = text.count('{')
    close_braces = text.count('}')

    if open_brackets > close_brackets:
        text += ']' * (open_brackets - close_brackets)
    if open_braces > close_braces:
        text += '}' * (open_braces - close_braces)

    return text

def extract_json(text):
    """Industry Standard: Repair-first JSON extraction."""
    if not isinstance(text, str) or not text.strip():
        raise ValueError("Empty input")
        
    cleaned = text.strip()
    
    try:
        return json.loads(cleaned)
    except json.JSONDecodeError:
        pass
        
    try:
        repaired = json_repair.loads(cleaned)
        if repaired:
            logger.warning("extract_json: AUTO-REPAIRED malformed JSON")
            return repaired
    except Exception:
        pass
        
    try:
        fenced = re.sub(r'^```(?:json)?\s*|\s*```$', '', cleaned, flags=re.MULTILINE)
        repaired = json_repair.loads(fenced)
        if repaired:
            logger.warning("extract_json: AUTO-REPAIRED fenced JSON")
            return repaired
    except Exception:
        pass
        
    logger.error("extract_json FAILED. payload_len=%d preview=%r", len(cleaned), cleaned[:500])
    raise ValueError("The AI output was too malformed to repair. Please click 'Copy Error for AI' and re-run the prompt.")
    
    # 0. Detect if the user pasted the prompt instead of the JSON
    if "IDEALOGY - CHIEF EXAMINER" in text or "REQUIRED JSON SCHEMA" in text:
        raise ValueError(
            "You pasted the PROMPT instructions instead of the AI's answer. "
            "Please copy the JSON output from ChatGPT/Gemini (it must start with '{' and end with '}')."
        )

    # 0. Fix AI double-escaping brackets (e.g. \\[ -> [ )
    text = text.replace('\\\\[', '[').replace('\\\\]', ']')
    text = text.replace('\\\\{', '{').replace('\\\\}', '}')

    # 1. Try direct parse
    try:
        return json.loads(text.strip())
    except json.JSONDecodeError:
        pass
        
    # 1.5 Auto-repair truncated JSON
    first = text.find('{')
    if first != -1:
        candidate = text[first:]
        try:
            repaired_trunc = _repair_truncated_json(candidate)
            parsed = json.loads(repaired_trunc)
            logger.warning("extract_json: AUTO-REPAIRED truncated JSON")
            return parsed
        except json.JSONDecodeError:
            pass

    # 2. Find outermost braces
    first, last = text.find("{"), text.rfind("}")
    if first != -1 and last > first:
        try:
            return json.loads(text[first:last + 1])
        except json.JSONDecodeError:
            pass
            
    # 3. Try markdown fence
    m = _FENCE_RE.search(text)
    if m:
        fenced_content = m.group(1).strip()
        if fenced_content:
            try:
                return json.loads(fenced_content)
            except json.JSONDecodeError:
                pass
                
    # 4. Auto-repair: try closing unclosed braces (truncation from AI)
    if first != -1 and last > first:
        candidate = text[first:]
        opens = candidate.count('{')
        closes = candidate.count('}')
        if opens > closes:
            # Try closing all open braces
            repaired = candidate + '}' * (opens - closes)
            try:
                parsed = json.loads(repaired)
                logger.warning("extract_json: AUTO-REPAIRED missing braces (%d adds)", opens - closes)
                return parsed
            except json.JSONDecodeError:
                pass

    # 5. Auto-repair: trailing commas
    if first != -1 and last > first:
        candidate = text[first:last + 1]
        repaired = re.sub(r',(\s*[}\]])', r'\1', candidate)
        if repaired != candidate:
            try:
                parsed = json.loads(repaired)
                logger.warning("extract_json: AUTO-REPAIRED trailing commas")
                return parsed
            except json.JSONDecodeError:
                pass

    # LOG failure with payload preview for admin debugging
    logger.error(
        "extract_json FAILED. payload_len=%d preview=%r",
        len(text), text[:800]
    )
    raise ValueError(
        "Invalid JSON: AI did not return a JSON object. "
        "Re-run the prompt in ChatGPT/Gemini and paste the COMPLETE response."
    )

def coerce_score(value, max_marks):
    if value is None or value == "":
        return None
    if isinstance(value, (int, float, Decimal)):
        d = Decimal(str(value))
    else:
        s = str(value).strip()
        if "/" in s:
            s = s.split("/", 1)[0].strip()
        s = re.sub(r"[^0-9.-]", "", s)
        if not s:
            return None
        try:
            d = Decimal(s)
        except InvalidOperation:
            return None
    if d < 0:
        d = Decimal("0")
    if max_marks is not None and d > max_marks:
        d = max_marks
    return d


def coerce_confidence(value):
    if value is None or value == "":
        return None
    try:
        d = Decimal(str(value))
    except InvalidOperation:
        return None
    if d < 0:
        return Decimal("0")
    if d > 1:
        return Decimal("1")
    return d


def normalize_mistakes(value):
    if not value:
        return []
    if isinstance(value, str):
        return [{"mistake_text": value, "correction_text": "", "error_type": ""}]
    if not isinstance(value, list):
        return []
    out = []
    for item in value:
        if isinstance(item, str):
            out.append({"mistake_text": item, "correction_text": "", "error_type": ""})
        elif isinstance(item, dict):
            out.append({
                "mistake_text": str(item.get("mistake_text") or item.get("student_wrote") or item.get("what_wrote") or ""),
                "correction_text": str(item.get("correction_text") or item.get("correct") or item.get("correct_version") or ""),
                "error_type": str(item.get("error_type") or item.get("type") or ""),
            })
    return out


def normalize_tasks(value):
    if not value:
        return []
    if isinstance(value, str):
        return [value]
    if isinstance(value, dict):
        desc = value.get("description") or value.get("task") or value.get("text")
        return [str(desc)] if desc else []
    if not isinstance(value, list):
        return []
    out = []
    for item in value:
        if isinstance(item, str):
            out.append(item)
        elif isinstance(item, dict):
            desc = item.get("description") or item.get("task") or item.get("text")
            if desc:
                out.append(str(desc))
    return out






def _norm_wvc(value):
    if not value:
        return []
    if isinstance(value, dict):
        value = [value]
    if not isinstance(value, list):
        return []
    out = []
    for item in value:
        if not isinstance(item, dict):
            continue
        out.append({
            "student_wrote": str(item.get("student_wrote") or item.get("student_answer") or ""),
            "correct_version": str(item.get("correct_version") or item.get("correction") or item.get("correct") or ""),
            "error_type": str(item.get("error_type") or item.get("type") or ""),
        })
    return out


def _norm_ec(value):
    if not isinstance(value, dict):
        return {"strength": "", "need": "", "suggestion": ""}
    return {
        "strength": str(value.get("strength") or ""),
        "need": str(value.get("need") or ""),
        "suggestion": str(value.get("suggestion") or ""),
    }


def normalize_questions(value):
    """Normalize a per-student questions array into a list of dicts."""
    if not value:
        return []
    if isinstance(value, dict):
        value = [value]
    if not isinstance(value, list):
        return []
    out = []
    for item in value:
        if not isinstance(item, dict):
            continue
        out.append({
            "subject": str(item.get("subject") or ""),
            "topic": str(item.get("topic") or ""),
            "question_text": str(item.get("question_text") or ""),
            "expected_answer": str(item.get("expected_answer") or ""),
            "rubric": str(item.get("rubric") or ""),
            "student_answer_transcribed": str(item.get("student_answer_transcribed") or item.get("ocr_text") or ""),
            "logical_analysis": str(item.get("logical_analysis") or item.get("rationale") or ""),
            "root_cause": str(item.get("root_cause") or ""),
            "concept_story": str(item.get("concept_story") or ""),
            "handwriting_analysis": item.get("handwriting_analysis") or {},
            "socratic_ladder": item.get("socratic_ladder") or [],
            "score_raw": item.get("score"),
            "max_marks_raw": item.get("max_marks"),
            "confidence_raw": item.get("confidence"),
            "mistakes_raw": item.get("mistakes"),
            "band": str(item.get("band") or ""),
            "kc_code": str(item.get("kc_code") or ""),
            "answer_source": str(item.get("answer_source") or ""),
            "wrong_vs_correct": _norm_wvc(item.get("wrong_vs_correct")),
            "expert_comment": _norm_ec(item.get("expert_comment")),
            "model_question_slug": str(item.get("model_question_slug") or ""),
            "framework_cited": str(item.get("framework_cited") or ""),
            "model_answer_with_story": str(item.get("model_answer_with_story") or ""),
        })
    return out





def _norm_task_objs(value):
    if not value:
        return []
    if isinstance(value, str):
        return [{"category": "", "title": value, "model_answer": "", "story_example": ""}]
    if isinstance(value, dict):
        value = [value]
    if not isinstance(value, list):
        return []
    out = []
    for item in value:
        if isinstance(item, str):
            out.append({"category": "", "title": item, "model_answer": "", "story_example": ""})
        elif isinstance(item, dict):
            title = item.get("title") or item.get("description") or item.get("task") or item.get("text") or ""
            out.append({
                "category": str(item.get("category") or ""),
                "title": str(title),
                "model_answer": str(item.get("model_answer") or ""),
                "story_example": str(item.get("story_example") or ""),
            })
    return out


def normalize_students(value):
    """Normalize the top-level students array. Each student has code + questions[].
    Also accepts the legacy single-question shape (wrap into a 1-item list).
    """
    if not isinstance(value, list):
        return []
    out = []
    for s in value:
        if not isinstance(s, dict):
            continue
        code = str(s.get("code") or "").strip()
        if not code:
            continue
        qs = s.get("questions")
        if qs:
            questions = normalize_questions(qs)
        else:
            questions = normalize_questions([{
                "subject": s.get("subject"),
                "topic": s.get("topic"),
                "question_text": s.get("question_text"),
                "expected_answer": s.get("expected_answer"),
                "rubric": s.get("rubric"),
                "student_answer_transcribed": s.get("ocr_text") or s.get("student_answer_transcribed"),
                "logical_analysis": s.get("rationale") or s.get("logical_analysis"),
                "root_cause": s.get("root_cause"),
                "score": s.get("score"),
                "max_marks": s.get("max_marks"),
                "confidence": s.get("confidence"),
                "mistakes": s.get("mistakes"),
            }])
        out.append({
            "code": code,
            "questions": questions,
            "next_day_tasks": _norm_task_objs(s.get("next_day_tasks")),
            "mastery_check": str(s.get("mastery_check") or ""),
            "overall_feedback": str(s.get("overall_feedback") or ""),
        })
    return out


# ── Urdu Nastaliq → Roman Urdu transliteration ──
_URDU_MAP = {
    'ا': 'a', 'آ': 'aa', 'ب': 'b', 'پ': 'p', 'ت': 't', 'ٹ': 't',
    'ث': 's', 'ج': 'j', 'چ': 'ch', 'ح': 'h', 'خ': 'kh', 'د': 'd',
    'ڈ': 'd', 'ذ': 'z', 'ر': 'r', 'ڑ': 'r', 'ز': 'z', 'ژ': 'zh',
    'س': 's', 'ش': 'sh', 'ص': 's', 'ض': 'z', 'ط': 't', 'ظ': 'z',
    'ع': 'a', 'غ': 'gh', 'ف': 'f', 'ق': 'q', 'ک': 'k', 'گ': 'g',
    'ل': 'l', 'م': 'm', 'ن': 'n', 'ں': 'n', 'و': 'o', 'ہ': 'h',
    'ھ': 'h', 'ء': '', 'ی': 'i', 'ے': 'e', 'ئ': 'i', 'ؤ': 'o',
    'ۓ': 'e', 'ۃ': 'h',
    'َ': 'a', 'ِ': 'i', 'ُ': 'u', 'ً': 'an', 'ٍ': 'in', 'ٌ': 'un',
    'ْ': '', 'ٰ': 'a', 'ّ': '',
    '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4',
    '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9',
    '،': ',', '۔': '.', '؟': '?', '؛': ';',
}

def romanize_urdu(text):
    """Convert Urdu Nastaliq characters to Roman Urdu (English alphabet)."""
    if not text:
        return text
    out = []
    for ch in str(text):
        if ch in _URDU_MAP:
            out.append(_URDU_MAP[ch])
        elif '\u0600' <= ch <= '\u06FF' or '\u0750' <= ch <= '\u077F':
            continue  # unknown Arabic char, skip
        else:
            out.append(ch)
    return ''.join(out)


def has_arabic_script(text):
    """True if text contains Arabic/Urdu Unicode characters."""
    if not text:
        return False
    return any('\u0600' <= ch <= '\u06FF' for ch in str(text))
