import pytest
from django.urls import reverse
from django.contrib.auth.models import Group, User
from django.test import Client

SAFE_STATUS_CODES = {200, 301, 302, 303, 403, 404, 405}

@pytest.fixture
def candidate_client(db):
    user = User.objects.create_user(username="candidate", password="password", email="candidate@test.com")
    client = Client()
    client.force_login(user)
    return client

@pytest.fixture
def superuser_client(db):
    user = User.objects.create_superuser(username="superuser", password="password", email="superuser@test.com")
    # Add to editor and manager groups to satisfy all custom mixins
    for group_name in ["physics_checker", "cid_user_manager"]:
        g, _ = Group.objects.get_or_create(name=group_name)
        user.groups.add(g)
    client = Client()
    client.force_login(user)
    return client

@pytest.fixture
def anonymous_client(db):
    return Client()

@pytest.fixture
def smoke_data(db, settings, tmp_path):
    from physics.models import Question, Exam, UserAnswer, Category
    settings.MEDIA_ROOT = str(tmp_path)

    create_user = User.objects.create_user(username="smoke_user", email="smoke_user@test.com")

    category, _ = Category.objects.get_or_create(category="Test Category")

    question = Question.objects.create(
        stem="test question stem",
        a="question a text",
        a_feedback="question a feedback",
        b="question b text",
        b_feedback="question b feedback",
        c="question c text",
        c_feedback="question c feedback",
        d="question d text",
        d_feedback="question d feedback",
        e="question e text",
        e_feedback="question e feedback",
        a_answer=True,
        b_answer=False,
        c_answer=True,
        d_answer=False,
        e_answer=True,
        category=category,
    )

    exam = Exam.objects.create(
        name="Test Physics Exam",
        exam_mode=True,
        active=True
    )
    exam.author.add(create_user)
    # Link question to exam
    from physics.models import ExamQuestionDetail
    ExamQuestionDetail.objects.create(exam=exam, question=question, sort_order=1)

    user_answer = UserAnswer.objects.create(
        user=create_user,
        exam=exam,
        question=question,
        a=True,
        b=False,
        c=True,
        d=False,
        e=True,
    )

    return {
        "question": question,
        "exam": exam,
        "user_answer": user_answer,
    }

URL_SPECS = [
    ("physics:question_view", None),
    ("physics:question_create", None),
    ("physics:question_create_exam", lambda d: {"pk": d["exam"].pk}),
    ("physics:question_detail", lambda d: {"pk": d["question"].pk}),
    ("physics:exam_markers", lambda d: {"pk": d["exam"].pk}),
    ("physics:exam_groups_edit", lambda d: {"pk": d["exam"].pk}),
    ("physics:exam_authors", lambda d: {"pk": d["exam"].pk}),
    ("physics:exam_clone", lambda d: {"exam_id": d["exam"].pk}),
    ("physics:exam_update", lambda d: {"pk": d["exam"].pk}),
    ("physics:exam_delete", lambda d: {"pk": d["exam"].pk}),
    ("physics:active_exams", None),
    ("physics:user_answer_table_view", None),
    ("physics:user_answer_view", lambda d: {"pk": d["user_answer"].pk}),
    ("physics:user_answer_delete", lambda d: {"pk": d["user_answer"].pk}),
    ("physics:exam_review_question_responses", lambda d: {"pk": d["exam"].pk, "q_index": 0}),
    ("physics:exam_review_question_summary", lambda d: {"pk": d["exam"].pk, "q_index": 0}),
    ("physics:index", None),
    ("physics:help", None),
]

@pytest.mark.django_db
@pytest.mark.parametrize("url_name, kwargs_lambda", URL_SPECS)
def test_url_smoke_anonymous(anonymous_client, smoke_data, url_name, kwargs_lambda):
    kwargs = kwargs_lambda(smoke_data) if kwargs_lambda else None
    url = reverse(url_name, kwargs=kwargs)
    response = anonymous_client.get(url, follow=False)
    assert response.status_code != 500, f"500 Server Error on {url_name} ({url}) for Anonymous"
    assert response.status_code in {200, 302, 403, 404}, f"Unexpected status code {response.status_code} on {url_name} for Anonymous"

@pytest.mark.django_db
@pytest.mark.parametrize("url_name, kwargs_lambda", URL_SPECS)
def test_url_smoke_candidate(candidate_client, smoke_data, url_name, kwargs_lambda):
    kwargs = kwargs_lambda(smoke_data) if kwargs_lambda else None
    url = reverse(url_name, kwargs=kwargs)
    response = candidate_client.get(url, follow=False)
    assert response.status_code != 500, f"500 Server Error on {url_name} ({url}) for Candidate"
    assert response.status_code in SAFE_STATUS_CODES, f"Unexpected status code {response.status_code} on {url_name} for Candidate"

@pytest.mark.django_db
@pytest.mark.parametrize("url_name, kwargs_lambda", URL_SPECS)
def test_url_smoke_superuser(superuser_client, smoke_data, url_name, kwargs_lambda):
    kwargs = kwargs_lambda(smoke_data) if kwargs_lambda else None
    url = reverse(url_name, kwargs=kwargs)
    response = superuser_client.get(url, follow=False)
    assert response.status_code != 500, f"500 Server Error on {url_name} ({url}) for Superuser"
    assert response.status_code in {200, 301, 302, 303, 403, 404}, f"Unexpected status code {response.status_code} on {url_name} for Superuser"
