import pytest
import tempfile
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/checker/manager groups to satisfy all custom mixins
    for group_name in ["rapid_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 rapids.models import Rapid, RapidImage, Exam, UserAnswer, Answer, Abnormality, Region, Examination
    settings.MEDIA_ROOT = str(tmp_path)

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

    # Create dummy supporting model objects
    abn, _ = Abnormality.objects.get_or_create(name="Test Abnormality")
    reg, _ = Region.objects.get_or_create(name="Test Region")
    exm_name, _ = Examination.objects.get_or_create(examination="Test Examination")

    question = Rapid.objects.create(
        laterality=Rapid.NONE,
        history="Test History",
        normal=False,
    )
    question.abnormality.add(abn)
    question.region.add(reg)
    question.examination.add(exm_name)

    # Mocking image
    image = tempfile.NamedTemporaryFile(
        dir=settings.MEDIA_ROOT, suffix=".jpg", delete=False
    )
    image.flush()
    image._committed = True
    # Save dummy content to prevent issues with PIL/DICOM hashing
    image.write(b"12345ABCD")
    image.seek(0)
    rapid_image = RapidImage(image=image.name, rapid=question)
    rapid_image.save()

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

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

    user_answer = UserAnswer.objects.create(
        user=create_user,
        exam=exam,
        question=question,
        normal=False,
        answer="testanswer",
        answer_compare="testanswer",
        score=Answer.MarkOptions.CORRECT,
    )

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

URL_SPECS = [
    ("rapids:question_viewer", None),
    ("rapids:question_view", None),
    ("rapids:question_json", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_json_unbased", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_save_annotation", lambda d: {"pk": d["question"].pk}),
    ("rapids:rapid_split", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_migrate_to_shorts", lambda d: {"pk": d["question"].pk}),
    ("rapids:rapid_clone", lambda d: {"pk": d["question"].pk}),
    ("rapids:rapid_scrap", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_delete", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_anonymise_dicom", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_add_exam", lambda d: {"question_id": d["question"].pk}),
    ("rapids:confirm_answer", lambda d: {"answer_id": d["answer"].pk}),
    ("rapids:delete_answer", lambda d: {"answer_id": d["answer"].pk}),
    ("rapids:mark", lambda d: {"exam_pk": d["exam"].pk, "sk": 0}),
    ("rapids:mark_all", lambda d: {"exam_pk": d["exam"].pk, "sk": 0}),
    ("rapids:mark_review", lambda d: {"exam_pk": d["exam"].pk, "sk": 0}),
    ("rapids:exam_markers", lambda d: {"pk": d["exam"].pk}),
    ("rapids:exam_groups_edit", lambda d: {"pk": d["exam"].pk}),
    ("rapids:exam_authors", lambda d: {"pk": d["exam"].pk}),
    ("rapids:exam_create", None),
    ("rapids:exam_clone", lambda d: {"exam_id": d["exam"].pk}),
    ("rapids:exam_update", lambda d: {"pk": d["exam"].pk}),
    ("rapids:exam_migrate_rapids_to_shorts", lambda d: {"pk": d["exam"].pk}),
    ("rapids:exam_delete", lambda d: {"pk": d["exam"].pk}),
    ("rapids:question_create", None),
    ("rapids:question_create_exam", lambda d: {"pk": d["exam"].pk}),
    ("rapids:create_region", None),
    ("rapids:create_abnormality", None),
    ("rapids:create_examination", None),
    ("rapids:rapid_update", lambda d: {"pk": d["question"].pk}),
    ("rapids:question_answer_update", lambda d: {"pk": d["question"].pk}),
    ("rapids:user_answer_table_view", None),
    ("rapids:user_answer_view", lambda d: {"pk": d["user_answer"].pk}),
    ("rapids:user_answer_delete", lambda d: {"pk": d["user_answer"].pk}),
    ("rapids:index", None),
    ("rapids: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, 400, 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 or response.status_code == 400, 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, 400, 403, 404}, f"Unexpected status code {response.status_code} on {url_name} for Superuser"
