"""split reports per modality side (pathology/imaging)

Revision ID: 20260930_split
Revises: 20260929_modality
Create Date: 2026-09-30 00:00:00.000000

One report per (order, modality): the radiologist works only the imaging
side, the lab only the pathology side. Historic mixed orders keep their
single record on the pathology side; new orders split at creation.

"""

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

revision: str = "20260930_split"
down_revision: str | None = "20260929_modality"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    modality = sa.Enum("pathology", "imaging", name="category_modality", create_type=False)
    op.add_column(
        "report",
        sa.Column("modality", modality, nullable=False, server_default="pathology"),
    )
    # Backfill: reports of imaging-only orders become imaging; mixed history
    # stays on the pathology side (single legal document, unchanged).
    op.execute(
        """
        UPDATE report SET modality = 'imaging'
        WHERE deleted_at IS NULL AND modality = 'pathology'
        AND order_id IN (
            SELECT o.id FROM visit_order o WHERE EXISTS (
                SELECT 1 FROM order_test ot
                JOIN test t ON t.id = ot.test_id
                JOIN test_category tc ON tc.id = t.category_id
                WHERE ot.order_id = o.id
                AND ot.status != 'cancelled'
                AND tc.modality = 'imaging'
            ) AND NOT EXISTS (
                SELECT 1 FROM order_test ot
                JOIN test t ON t.id = ot.test_id
                JOIN test_category tc ON tc.id = t.category_id
                WHERE ot.order_id = o.id
                AND ot.status != 'cancelled'
                AND tc.modality != 'imaging'
            )
        )
        """
    )
    op.drop_constraint("uq_report_order_id_version", "report", type_="unique")
    op.create_unique_constraint(
        "uq_report_order_version_modality", "report", ["order_id", "modality", "version"]
    )


def downgrade() -> None:
    op.drop_constraint("uq_report_order_version_modality", "report", type_="unique")
    op.create_unique_constraint("uq_report_order_id_version", "report", ["order_id", "version"])
    op.drop_column("report", "modality")
