
import re
from difflib import SequenceMatcher

def grade_student_answer(student_text, model_text, max_marks=5):
    """
    Multistep Reasoning Engine.
    Compares the student's text against the model answer.
    Calculates a similarity score and extracts missing keywords.
    """
    if not student_text or not model_text:
        return {'outcome': 'WRONG', 'score': 0, 'feedback': 'Answer or model answer is empty.'}

    # Clean text
    s_clean = re.sub(r'[^a-zA-Z0-9\s]', '', student_text.lower())
    m_clean = re.sub(r'[^a-zA-Z0-9\s]', '', model_text.lower())
    
    # 1. Overall Similarity (Sequence Matcher)
    similarity = SequenceMatcher(None, s_clean, m_clean).ratio()
    
    # 2. Keyword Extraction (Simple heuristic: words > 4 chars)
    model_keywords = set([w for w in m_clean.split() if len(w) > 4])
    student_keywords = set([w for w in s_clean.split() if len(w) > 4])
    
    missing_keywords = model_keywords - student_keywords
    
    # 3. Determine Outcome
    if similarity > 0.85:
        outcome = 'CORRECT'
        score = max_marks
        feedback = "Excellent! Your answer covers all key points."
    elif similarity > 0.45:
        outcome = 'PARTIAL'
        score = int(max_marks * 0.5)
        feedback = f"Partial marks. You missed some key concepts: {', '.join(list(missing_keywords)[:3])}"
    else:
        outcome = 'WRONG'
        score = 0
        feedback = f"Needs improvement. Focus on explaining: {', '.join(list(missing_keywords)[:3])}"

    return {
        'outcome': outcome,
        'score': score,
        'similarity': round(similarity, 2),
        'missing_keywords': list(missing_keywords),
        'feedback': feedback
    }
