from __future__ import annotations

import pytest
from django.urls import reverse

from atlas.models import SeriesImage, UncategorisedDicom


@pytest.mark.django_db
def test_user_uploads_partial_import_button_prefers_case_for_hash_matched_series(
    client,
    admin_user,
    create_series,
    create_case,
    make_case,
):
    client.force_login(admin_user)

    primary_case = create_case
    primary_case.author.add(admin_user)

    secondary_case = make_case(title="Secondary Case")
    secondary_case.author.add(admin_user)

    existing_series = create_series
    existing_series.series_instance_uid = "atlas-series-1"
    existing_series.study_instance_uid = "study-1"
    existing_series.save(update_fields=["series_instance_uid", "study_instance_uid"])

    primary_case.series.add(existing_series)
    secondary_case.series.add(existing_series)

    SeriesImage.objects.create(series=existing_series, image_blake3_hash="shared-hash")

    UncategorisedDicom.objects.bulk_create(
        [
            UncategorisedDicom(
                image="pending-upload.dcm",
                user=admin_user,
                series_instance_uid="uploaded-series-1",
                image_blake3_hash="shared-hash",
                basic_dicom_tags={
                    "SeriesInstanceUID": "uploaded-series-1",
                    "StudyInstanceUID": "study-1",
                    "StudyDescription": "Shared study",
                    "SeriesDescription": "Uploaded series",
                    "Modality": "CT",
                },
            )
        ]
    )

    response = client.get(reverse("atlas:user_uploads"))

    assert response.status_code == 200
    content = response.content.decode("utf-8")
    assert 'class="btn btn-sm btn-warning import-partial-series-btn"' in content
    assert f'data-case-id="{primary_case.pk}"' in content


@pytest.mark.django_db
def test_user_uploads_patient_grouping_and_select2(client, admin_user):
    client.force_login(admin_user)

    # Create UncategorisedDicom with PatientID tag using bulk_create to avoid reading non-existent file
    UncategorisedDicom.objects.bulk_create(
        [
            UncategorisedDicom(
                image="pending-upload-patient.dcm",
                user=admin_user,
                series_instance_uid="uploaded-series-patient-1",
                basic_dicom_tags={
                    "SeriesInstanceUID": "uploaded-series-patient-1",
                    "StudyInstanceUID": "study-patient-1",
                    "StudyDescription": "Patient Study 1",
                    "SeriesDescription": "Uploaded series",
                    "Modality": "CT",
                    "PatientID": "PAT-999-XYZ",
                },
            )
        ]
    )

    response = client.get(reverse("atlas:user_uploads"))
    assert response.status_code == 200
    content = response.content.decode("utf-8")

    # Verify patient grouping is rendered
    assert "PAT-999-XYZ" in content
    assert "Patient ID:" in content
    assert "select-all-patient-btn" in content

    # Verify form autocomplete widgets are in context
    form = response.context["case_series_form"]
    from dal import autocomplete
    assert isinstance(form.fields["condition"].widget, autocomplete.ModelSelect2Multiple)
    assert isinstance(form.fields["presentation"].widget, autocomplete.ModelSelect2Multiple)
    assert isinstance(form.fields["procedures"].widget, autocomplete.ModelSelect2Multiple)