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 ["anatomy_editor", "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 anatomy.models import AnatomyQuestion, Exam, UserAnswer, QuestionType, Structure, Answer
    import tempfile

    settings.MEDIA_ROOT = str(tmp_path)

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

    qtype, _ = QuestionType.objects.get_or_create(text="Test QType")
    structure, _ = Structure.objects.get_or_create(name="Test Structure")

    image_file = tempfile.NamedTemporaryFile(dir=settings.MEDIA_ROOT, suffix=".jpg", delete=False)

    question = AnatomyQuestion.objects.create(
        question_type=qtype,
        structure=structure,
        image=image_file.name
    )

    exam = Exam.objects.create(
        name="Test Anatomy Exam",
        exam_mode=True,
        active=True
    )
    exam.author.add(create_user)

    answer = Answer.objects.create(
        question=question,
        answer="testanswer",
        status=Answer.MarkOptions.CORRECT
    )

    user_answer = UserAnswer.objects.create(
        user=create_user,
        exam=exam,
        question=question
    )

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

URL_SPECS = [
    ("anatomy:question_view", None),
    ("anatomy:question_create", None),
    ("anatomy:anatomy_question_update", lambda d: {"pk": d["question"].pk}),
    ("anatomy:question_answer_update", lambda d: {"pk": d["question"].pk}),
    ("anatomy:question_clone", lambda d: {"pk": d["question"].pk}),
    ("anatomy:question_delete", lambda d: {"pk": d["question"].pk}),
    ("anatomy:exam_markers", lambda d: {"pk": d["exam"].pk}),
    ("anatomy:exam_groups_edit", lambda d: {"pk": d["exam"].pk}),
    ("anatomy:exam_authors", lambda d: {"pk": d["exam"].pk}),
    ("anatomy:exam_create", None),
    ("anatomy:exam_clone", lambda d: {"exam_id": d["exam"].pk}),
    ("anatomy:exam_update", lambda d: {"pk": d["exam"].pk}),
    ("anatomy:exam_delete", lambda d: {"pk": d["exam"].pk}),
    ("anatomy:user_answer_table_view", None),
    ("anatomy:user_answer_view", lambda d: {"pk": d["user_answer"].pk}),
    ("anatomy:user_answer_delete", lambda d: {"pk": d["user_answer"].pk}),
    ("anatomy:mark2_overview", lambda d: {"pk": d["exam"].pk}),
    ("anatomy:index", None),
    ("anatomy: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}, f"Unexpected status code {response.status_code} on {url_name} for Superuser"
