"""FlowRunner — executes a FlowDefinition as a state machine."""
import json
from django.utils import timezone


class FlowRunner:
    """Enroll, advance, and evaluate a student through a flow."""

    @staticmethod
    def start(flow, student=None, preview_by=None):
        """Create a FlowRun for the student starting at START node."""
        from exams.models_flow import FlowNode, FlowRun, FlowRunEvent
        start_node = flow.nodes.filter(node_type='START').first()
        if not start_node:
            raise ValueError("Flow has no START node")
        first_edge = start_node.outgoing_edges.order_by('priority').first()
        entry_node = first_edge.target_node if first_edge else start_node
        run = FlowRun.objects.create(
            flow=flow, student=student, preview_by=preview_by, current_node=entry_node,
            state_json=json.dumps({'answers': [], 'consecutive_correct': 0, 'path_taken': []}),
            mastery_level='LEARNING',
        )
        FlowRunEvent.objects.create(
            run=run, event_type='ENTERED', node=entry_node,
            data_json=json.dumps({'entry': True}),
        )
        return run

    @staticmethod
    def advance(run, answer=None, timed_out=False, answer_alt=None):
        """Process an answer and move to next node by edge priority."""
        from exams.models_flow import FlowRunEvent
        current = run.current_node
        if not current:
            raise ValueError("Run has no current node")

        state = json.loads(run.state_json or '{}')
        state.setdefault('answers', [])
        state.setdefault('consecutive_correct', 0)
        state.setdefault('path_taken', [])

        try:
            cfg = json.loads(current.config_json or '{}')
        except Exception:
            cfg = {}

        is_correct = False
        is_auto_pass = cfg.get('is_selection') or cfg.get('type') == 'read'

        if is_auto_pass:
            is_correct = True
            state['answers'].append({'node_id': current.pk, 'answer': answer, 'correct': True, 'auto_pass': True})
            FlowRunEvent.objects.create(
                run=run, event_type='ANSWERED', node=current,
                data_json=json.dumps({'answer': answer, 'correct': True, 'auto_pass': True}),
            )
        elif answer is not None or answer_alt is not None:
            is_correct = FlowRunner._check_answer(current, answer, answer_alt)
            state['answers'].append({'node_id': current.pk, 'answer': answer, 'correct': is_correct})
            if is_correct:
                state['consecutive_correct'] += 1
                run.score += 10
            else:
                state['consecutive_correct'] = 0
            FlowRunEvent.objects.create(
                run=run, event_type='ANSWERED', node=current,
                data_json=json.dumps({'answer': answer, 'correct': is_correct}),
            )

        if timed_out:
            FlowRunEvent.objects.create(
                run=run, event_type='TIMED_OUT', node=current,
                data_json=json.dumps({}),
            )

        edges = current.outgoing_edges.order_by('priority')
        next_node = None
        for edge in edges:
            if FlowRunner._edge_matches(edge, is_correct, timed_out, state, answer):
                next_node = edge.target_node
                state['path_taken'].append(edge.label or f'p{edge.priority}')
                FlowRunEvent.objects.create(
                    run=run, event_type='BRANCHED', node=next_node,
                    data_json=json.dumps({'via': edge.label}),
                )
                break

        if next_node is None:
            run.status = 'COMPLETED'
            run.completed_at = timezone.now()
            run.state_json = json.dumps(state)
            run.save()
            FlowRunEvent.objects.create(
                run=run, event_type='COMPLETED', node=current,
                data_json=json.dumps({'reason': 'no_matching_edge'}),
            )
            return run

        if state['consecutive_correct'] >= run.flow.mastery_threshold:
            run.mastery_level = 'MASTERED'

        if next_node.node_type == 'END':
            run.status = 'COMPLETED'
            run.completed_at = timezone.now()

        run.current_node = next_node
        run.state_json = json.dumps(state)
        run.save()
        return run

    @staticmethod
    def _check_answer(node, answer, answer_alt=None):
        """Type-aware matching:
        - reorder: exact sequence (only whitespace/case flexible)
        - fill_blank: exact for short, SequenceMatcher for long
        - mcq/matching: exact option match
        """
        import difflib
        cfg = json.loads(node.config_json or '{}')
        node_type = (cfg.get('type') or '').lower()
        correct_en = str(cfg.get('correct_answer', '') or '').strip()
        correct_ur = str(cfg.get('correct_answer_alt', '') or '').strip()

        def norm(s):
            return ' '.join(str(s or '').strip().lower().split())

        student = norm(answer)
        student_alt = norm(answer_alt)
        correct_vals = [norm(c) for c in [correct_en, correct_ur] if c]
        if not correct_vals:
            return False
        if not student and not student_alt:
            return False

        # REORDER: exact sequence match (very strict)
        if node_type == 'reorder':
            for c in correct_vals:
                if student == c:
                    return True
                if student_alt and student_alt == c:
                    return True
            return False

        # FILL_BLANK: exact or SequenceMatcher for long
        if node_type == 'fill_blank':
            for c in correct_vals:
                for s in [student, student_alt]:
                    if not s:
                        continue
                    if s == c:
                        return True
                    c_words = len(c.split())
                    s_words = len(s.split())
                    if abs(c_words - s_words) > 2:
                        continue
                    threshold = 0.85 if c_words <= 3 else 0.90
                    if difflib.SequenceMatcher(None, s, c).ratio() >= threshold:
                        return True
            return False

        # MCQ / MATCHING / other: exact
        for c in correct_vals:
            if student == c or (student_alt and student_alt == c):
                return True
        return False

    @staticmethod
    def _edge_matches(edge, is_correct, timed_out, state, answer=None):
        """Evaluate edge condition. Empty = always match."""
        cond = json.loads(edge.condition_json or '{}')
        if not cond:
            return True
        if cond.get('if') == 'correct':
            return is_correct
        if cond.get('if') == 'wrong':
            return not is_correct and not timed_out
        if cond.get('if') == 'timeout':
            return timed_out
        if cond.get('if') == 'answer_equals':
            return str(answer or '').strip().lower() == str(cond.get('value', '')).strip().lower()
        if cond.get('if') == 'consecutive_correct':
            return state['consecutive_correct'] >= cond.get('min', 1)
        return False
