"""phase 3 aqmm engagement level rework

Revision ID: 20260624_phase_3_aqmm_engagement_level_rework
Revises: 20260623_phase_2_1_digital_client_acceptance_workflow
Create Date: 2026-06-24
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa

revision = "20260624_phase_3_aqmm_engagement_level_rework"
down_revision = "20260623_phase_2_1_digital_client_acceptance_workflow"
branch_labels = None
depends_on = None


def _has_table(bind, table_name: str) -> bool:
    return sa.inspect(bind).has_table(table_name)


def _has_column(bind, table_name: str, column_name: str) -> bool:
    if not _has_table(bind, table_name):
        return False
    return column_name in {c["name"] for c in sa.inspect(bind).get_columns(table_name)}


def _add_column_once(bind, table: str, column: sa.Column) -> None:
    if not _has_column(bind, table, column.name):
        with op.batch_alter_table(table) as batch:
            batch.add_column(column)


def upgrade() -> None:
    bind = op.get_bind()

    if _has_table(bind, "client_service_subscriptions"):
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_workflow_required", sa.Boolean(), nullable=False, server_default=sa.false()))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_workflow_status", sa.String(length=40), nullable=False, server_default="not_required"))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_acceptance_status", sa.String(length=40), nullable=False, server_default="not_required"))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_independence_status", sa.String(length=40), nullable=False, server_default="not_required"))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_conflict_status", sa.String(length=40), nullable=False, server_default="not_required"))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_kyc_status", sa.String(length=40), nullable=False, server_default="not_required"))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_engagement_letter_status", sa.String(length=40), nullable=False, server_default="not_required"))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_approved_by_user_id", sa.Integer(), nullable=True))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_approved_at_utc", sa.DateTime(timezone=True), nullable=True))
        _add_column_once(bind, "client_service_subscriptions", sa.Column("quality_block_reason", sa.Text(), nullable=True))

        # Existing assurance engagements become pending AQMM acceptance unless already manually approved later.
        op.execute("""
            UPDATE client_service_subscriptions
            SET quality_workflow_required = TRUE,
                quality_workflow_status = 'pending_acceptance',
                quality_acceptance_status = 'pending_acceptance',
                quality_independence_status = 'pending_declarations',
                quality_conflict_status = 'pending_declarations',
                quality_kyc_status = 'pending_verification',
                quality_engagement_letter_status = 'pending_client_acceptance',
                quality_block_reason = 'AQMM acceptance workflow pending for assurance engagement.'
            WHERE lower(COALESCE(engagement_type, '')) = 'assurance'
              AND COALESCE(quality_acceptance_status, 'not_required') <> 'approved'
        """)

    if not _has_table(bind, "engagement_quality_declarations"):
        op.create_table(
            "engagement_quality_declarations",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
            sa.Column("branch_id", sa.Integer(), sa.ForeignKey("branches.id", ondelete="SET NULL"), nullable=True),
            sa.Column("client_id", sa.Integer(), sa.ForeignKey("clients.id", ondelete="CASCADE"), nullable=False),
            sa.Column("subscription_id", sa.Integer(), sa.ForeignKey("client_service_subscriptions.id", ondelete="CASCADE"), nullable=False),
            sa.Column("declaration_type", sa.String(length=40), nullable=False),
            sa.Column("requested_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
            sa.Column("requested_role", sa.String(length=80), nullable=True),
            sa.Column("status", sa.String(length=40), nullable=False, server_default="pending"),
            sa.Column("declaration_text", sa.Text(), nullable=True),
            sa.Column("response_notes", sa.Text(), nullable=True),
            sa.Column("responded_at_utc", sa.DateTime(timezone=True), nullable=True),
            sa.Column("ip_address", sa.String(length=80), nullable=True),
            sa.Column("user_agent", sa.String(length=500), nullable=True),
            sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.UniqueConstraint("subscription_id", "declaration_type", "requested_user_id", name="uq_engagement_quality_declaration_user_type"),
        )

    if not _has_table(bind, "engagement_kyc_verifications"):
        op.create_table(
            "engagement_kyc_verifications",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
            sa.Column("branch_id", sa.Integer(), sa.ForeignKey("branches.id", ondelete="SET NULL"), nullable=True),
            sa.Column("client_id", sa.Integer(), sa.ForeignKey("clients.id", ondelete="CASCADE"), nullable=False),
            sa.Column("subscription_id", sa.Integer(), sa.ForeignKey("client_service_subscriptions.id", ondelete="CASCADE"), nullable=False),
            sa.Column("status", sa.String(length=40), nullable=False, server_default="pending_verification"),
            sa.Column("source", sa.String(length=80), nullable=False, server_default="permanent_documents"),
            sa.Column("verification_notes", sa.Text(), nullable=True),
            sa.Column("verified_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("verified_at_utc", sa.DateTime(timezone=True), nullable=True),
            sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
        )

    if not _has_table(bind, "engagement_letters"):
        op.create_table(
            "engagement_letters",
            sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
            sa.Column("tenant_id", sa.Integer(), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
            sa.Column("branch_id", sa.Integer(), sa.ForeignKey("branches.id", ondelete="SET NULL"), nullable=True),
            sa.Column("client_id", sa.Integer(), sa.ForeignKey("clients.id", ondelete="CASCADE"), nullable=False),
            sa.Column("subscription_id", sa.Integer(), sa.ForeignKey("client_service_subscriptions.id", ondelete="CASCADE"), nullable=False),
            sa.Column("title", sa.String(length=255), nullable=False, server_default="Engagement Letter"),
            sa.Column("version_no", sa.Integer(), nullable=False, server_default="1"),
            sa.Column("status", sa.String(length=50), nullable=False, server_default="draft_pending"),
            sa.Column("acceptance_mode", sa.String(length=40), nullable=True),
            sa.Column("body_text", sa.Text(), nullable=True),
            sa.Column("pdf_sha256", sa.String(length=128), nullable=True),
            sa.Column("manual_upload_filename", sa.String(length=255), nullable=True),
            sa.Column("manual_upload_path", sa.String(length=500), nullable=True),
            sa.Column("client_acceptance_declaration", sa.Text(), nullable=True),
            sa.Column("partner_approved_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("partner_approved_at_utc", sa.DateTime(timezone=True), nullable=True),
            sa.Column("client_accepted_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("client_accepted_at_utc", sa.DateTime(timezone=True), nullable=True),
            sa.Column("manual_verified_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("manual_verified_at_utc", sa.DateTime(timezone=True), nullable=True),
            sa.Column("ip_address", sa.String(length=80), nullable=True),
            sa.Column("user_agent", sa.String(length=500), nullable=True),
            sa.Column("created_by_user_id", sa.Integer(), sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=True),
            sa.Column("created_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
            sa.Column("updated_at_utc", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")),
        )


def downgrade() -> None:
    bind = op.get_bind()
    for table in ["engagement_letters", "engagement_kyc_verifications", "engagement_quality_declarations"]:
        if _has_table(bind, table):
            op.drop_table(table)

    if _has_table(bind, "client_service_subscriptions"):
        for col in [
            "quality_block_reason",
            "quality_approved_at_utc",
            "quality_approved_by_user_id",
            "quality_engagement_letter_status",
            "quality_kyc_status",
            "quality_conflict_status",
            "quality_independence_status",
            "quality_acceptance_status",
            "quality_workflow_status",
            "quality_workflow_required",
        ]:
            if _has_column(bind, "client_service_subscriptions", col):
                with op.batch_alter_table("client_service_subscriptions") as batch:
                    batch.drop_column(col)
