import json
import pytest
from django.urls import reverse
from django.utils import timezone
from rapids.models import Exam, Rapid as Question, UserAnswer, Answer
from generic.models import CidUser, CidUserExam, ExamUserStatus
from django.contrib.auth.models import User

@pytest.fixture
def test_setup(db):
    # Create a test candidate
    cid_user = CidUser.objects.create(cid=9999, passcode="pass123", name="RTS Candidate")
    
    # Create an exam
    exam = Exam.objects.create(name="RTS Integration Exam", exam_mode=True, active=True)
    exam.valid_cid_users.add(cid_user)
    
    # Create questions
    q1 = Question.objects.create(history="Q1 History", normal=True)
    q1.exams.add(exam)
    
    # Create correct answers
    Answer.objects.create(question=q1, answer="Normal", answer_compare="Normal", status=Answer.MarkOptions.CORRECT)
    
    return {
        "cid_user": cid_user,
        "exam": exam,
        "q1": q1,
    }

def test_autosubmit_in_progress(client, test_setup):
    exam = test_setup["exam"]
    cid_user = test_setup["cid_user"]
    q1 = test_setup["q1"]
    
    answers = [
        {
            "aid": "session-1",
            "cid": str(cid_user.cid),
            "eid": f"rapid/{exam.pk}",
            "qid": q1.pk,
            "qidn": "1",
            "passcode": cid_user.passcode,
            "ans": "Normal",
            "time_answered": "2026-06-29T12:00:00.000Z",
        }
    ]
    
    payload = {
        "eid": f"rapid/{exam.pk}",
        "cid": str(cid_user.cid),
        "start_time": 1782730000.0,
        "answers": json.dumps(answers),
        "in_progress": "true",
    }
    
    response = client.post(reverse("rapids:exam_answers_submit"), payload)
    assert response.status_code == 200
    data = response.json()
    assert data["success"] is True
    assert data["question_count"] == 1
    
    # Verify answers stored with correct timestamp
    user_answer = UserAnswer.objects.get(exam=exam, question=q1, cid=cid_user.cid)
    assert user_answer.answer == "Normal"
    assert user_answer.time_answered is not None
    assert user_answer.time_answered.year == 2026
    assert user_answer.time_answered.month == 6
    assert user_answer.time_answered.day == 29
    
    # Verify exam session is NOT complete / finalized
    cid_user_exam = CidUserExam.objects.get(object_id=exam.pk, cid_user=cid_user)
    assert cid_user_exam.end_time is None
    assert cid_user_exam.completed is False
    assert not ExamUserStatus.objects.filter(cid_user_exam=cid_user_exam, status="submitted").exists()
    assert ExamUserStatus.objects.filter(cid_user_exam=cid_user_exam, status="autosaved").exists()

def test_final_submit(client, test_setup):
    exam = test_setup["exam"]
    cid_user = test_setup["cid_user"]
    q1 = test_setup["q1"]
    
    answers = [
        {
            "aid": "session-1",
            "cid": str(cid_user.cid),
            "eid": f"rapid/{exam.pk}",
            "qid": q1.pk,
            "qidn": "1",
            "passcode": cid_user.passcode,
            "ans": "Normal",
            "time_answered": "2026-06-29T12:00:00.000Z",
        }
    ]
    
    payload = {
        "eid": f"rapid/{exam.pk}",
        "cid": str(cid_user.cid),
        "start_time": 1782730000.0,
        "answers": json.dumps(answers),
        # in_progress absent (defaults to false)
    }
    
    response = client.post(reverse("rapids:exam_answers_submit"), payload)
    assert response.status_code == 200
    data = response.json()
    assert data["success"] is True
    
    # Verify exam session IS complete / finalized
    cid_user_exam = CidUserExam.objects.get(object_id=exam.pk, cid_user=cid_user)
    assert cid_user_exam.end_time is not None
    assert ExamUserStatus.objects.filter(cid_user_exam=cid_user_exam, status="submitted").exists()
