import logging

logger = logging.getLogger(__name__)

def validate_ai_grading_response(payload: dict, max_marks: float = 10.0) -> tuple[bool, str]:
    """
    INDUSTRY STANDARD: Strict Schema & Contradiction Validation for LLM Outputs.
    Zero Tolerance Policy for contradictory data.
    Returns: (is_valid, error_message)
    """
    if not isinstance(payload, dict):
        return False, "Payload must be a JSON object."

    # 1. Check for Explicit Error Flags from the AI
    if payload.get('error') == 'IMAGE_MISSING':
        return False, "AI reported missing image. Please re-upload the image to the AI or grade manually."

    # 2. Extract Score and Band (Handle both flat single-paste and nested bulk-paste schemas)
    score = payload.get('score')
    band = str(payload.get('band', '')).lower()
    outcome = str(payload.get('outcome', '')).lower()

    # If it's the nested master prompt schema (bulk paste)
    if score is None and 'students' in payload:
        try:
            q_data = payload['students'][0]['questions'][0]
            score = q_data.get('score')
            band = str(q_data.get('band', '')).lower()
            outcome = str(q_data.get('outcome', '')).lower()
        except (IndexError, KeyError, TypeError):
            return False, "JSON structure missing required 'students[0].questions[0]' fields."

    # 3. The Contradiction Check (The Referee Law)
    try:
        if score is not None:
            score_val = float(score)
            
            # Calculate percentage
            pct = (score_val / max_marks) * 100 if max_marks > 0 else 0
            
            # Check for the 100% + Wrong contradiction
            if pct >= 80 and (band in ('wrong', 'poor', 'below average') or outcome == 'wrong'):
                return False, f"AI CONTRADICTION: Score is {pct:.0f}% but Band/Outcome is '{band or outcome}'. Please re-prompt the AI to fix this contradiction."
                
    except (ValueError, TypeError):
        return False, "Score must be a valid number."

    return True, ""
