"""Rubric-based grading for physical test uploads.
Expected rubric schema (JSON):
    {
      "expected_answer": "...",
      "keywords": ["kw1", "kw2", ...],
      "min_keyword_matches": 2,
      "forbidden_keywords": [...]
    }
Outcome thresholds (AERA/APA/NCME 2014):
    CORRECT  if similarity >= 0.80  OR  keyword_matches >= min_keyword_matches
    PARTIAL  if similarity >= 0.45  OR  keyword_matches >= 1
    WRONG    otherwise
"""
import re
from difflib import SequenceMatcher


def _clean(text):
    return re.sub(r'[^a-zA-Z0-9\u0600-\u06FF\s]', ' ', (text or '').lower())


def grade_physical_test(ocr_text, rubric, max_marks=5):
    """Grade OCR text against rubric. Returns dict with score, outcome, feedback."""
    if not ocr_text or not rubric:
        return _result(0, max_marks, 'WRONG', [], [], 'Missing input.')

    expected = rubric.get('expected_answer', '') or ''
    keywords = [k.lower().strip() for k in rubric.get('keywords', []) if k]
    forbidden = [k.lower().strip() for k in rubric.get('forbidden_keywords', []) if k]
    min_match = int(rubric.get('min_keyword_matches', max(1, len(keywords) // 2)))

    ocr_clean = _clean(ocr_text)
    expected_clean = _clean(expected)

    similarity = SequenceMatcher(None, ocr_clean, expected_clean).ratio()

    matched = [k for k in keywords if k in ocr_clean]
    missing = [k for k in keywords if k not in ocr_clean]
    violated = [k for k in forbidden if k in ocr_clean]

    if violated:
        outcome, pct = 'WRONG', 0.0
    elif similarity >= 0.80 or len(matched) >= min_match:
        outcome, pct = 'CORRECT', 1.0
    elif similarity >= 0.45 or len(matched) >= 1:
        outcome, pct = 'PARTIAL', 0.5
    else:
        outcome, pct = 'WRONG', 0.0

    score = round(max_marks * pct, 2)
    feedback = (
        f'Matched {len(matched)}/{len(keywords)} keywords '
        f'(similarity {round(similarity*100)}%). '
        f'Missing: {", ".join(missing[:3]) or "none"}'
    )
    if violated:
        feedback = f'Forbidden terms used: {", ".join(violated[:3])}. Score capped.'

    return _result(score, max_marks, outcome, matched, missing, feedback)


def _result(score, max_marks, outcome, matched, missing, feedback):
    pct = round((score / max_marks * 100) if max_marks else 0, 1)
    return {
        'outcome': outcome,
        'score': score,
        'max_marks': max_marks,
        'percentage': pct,
        'matched_keywords': matched,
        'missing_keywords': missing,
        'feedback': feedback,
    }
