"""add AI decision feedback and workflow outcome ledger

Revision ID: 20260714_0003
Revises: 20260713_0002
Create Date: 2026-07-14 10:30:00
"""

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "20260714_0003"
down_revision: str | None = "20260713_0002"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # 为新账本的复合外键补充租户级唯一目标，阻止跨租户关联。
    op.create_unique_constraint(
        "uq_expense_cases_tenant_id",
        "expense_cases",
        ["tenant_id", "id"],
    )
    op.create_unique_constraint(
        "uq_business_events_tenant_case_id",
        "business_events",
        ["tenant_id", "expense_case_id", "id"],
    )

    op.create_table(
        "ai_decisions",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("expense_case_id", sa.String(length=36), nullable=False),
        sa.Column("business_event_id", sa.String(length=36), nullable=True),
        sa.Column("expense_claim_id", sa.String(length=36), nullable=False),
        sa.Column("agent_run_id", sa.String(length=120), nullable=True),
        sa.Column("correlation_id", sa.String(length=64), nullable=False),
        sa.Column("subject_type", sa.String(length=50), nullable=False),
        sa.Column("subject_id", sa.String(length=100), nullable=False),
        sa.Column("decision_type", sa.String(length=80), nullable=False),
        sa.Column("decision_source", sa.String(length=20), nullable=False),
        sa.Column("status", sa.String(length=20), nullable=False),
        sa.Column("automation_mode", sa.String(length=40), nullable=False),
        sa.Column("confidence", sa.Numeric(precision=5, scale=4), nullable=True),
        sa.Column("suggestion_json", sa.JSON(), nullable=False),
        sa.Column("evidence_json", sa.JSON(), nullable=False),
        sa.Column("version_json", sa.JSON(), nullable=False),
        sa.Column("schema_version", sa.Integer(), nullable=False),
        sa.Column(
            "training_eligible",
            sa.Boolean(),
            server_default=sa.false(),
            nullable=False,
        ),
        sa.Column("idempotency_key", sa.String(length=120), nullable=False),
        sa.Column("content_fingerprint", sa.String(length=71), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.CheckConstraint(
            "confidence IS NULL OR (confidence >= 0 AND confidence <= 1)",
            name="ck_ai_decisions_confidence",
        ),
        sa.CheckConstraint(
            "status IN ('suggested', 'accepted', 'edited', 'rejected', "
            "'ignored', 'executed', 'rolled_back')",
            name="ck_ai_decisions_status",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "expense_case_id", "business_event_id"],
            [
                "business_events.tenant_id",
                "business_events.expense_case_id",
                "business_events.id",
            ],
            name="fk_ai_decisions_tenant_event",
            ondelete="RESTRICT",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "expense_case_id"],
            ["expense_cases.tenant_id", "expense_cases.id"],
            name="fk_ai_decisions_tenant_case",
            ondelete="RESTRICT",
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint("tenant_id", "id", name="uq_ai_decisions_tenant_id"),
        sa.UniqueConstraint(
            "tenant_id",
            "expense_case_id",
            "id",
            name="uq_ai_decisions_tenant_case_id",
        ),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_ai_decisions_tenant_idempotency",
        ),
    )
    op.create_index(
        "ix_ai_decisions_tenant_case_time",
        "ai_decisions",
        ["tenant_id", "expense_case_id", "created_at"],
    )
    op.create_index(
        "ix_ai_decisions_tenant_subject",
        "ai_decisions",
        ["tenant_id", "subject_type", "subject_id"],
    )
    op.create_index("ix_ai_decisions_expense_claim_id", "ai_decisions", ["expense_claim_id"])
    op.create_index("ix_ai_decisions_agent_run_id", "ai_decisions", ["agent_run_id"])
    op.create_index("ix_ai_decisions_correlation_id", "ai_decisions", ["correlation_id"])

    op.create_table(
        "ai_decision_feedback",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("decision_id", sa.String(length=36), nullable=False),
        sa.Column("expense_claim_id", sa.String(length=36), nullable=False),
        sa.Column("correlation_id", sa.String(length=64), nullable=False),
        sa.Column("feedback_type", sa.String(length=20), nullable=False),
        sa.Column("action_type", sa.String(length=30), nullable=False),
        sa.Column("actor_id", sa.String(length=120), nullable=False),
        sa.Column("actor_type", sa.String(length=30), nullable=False),
        sa.Column("evidence_source", sa.String(length=40), nullable=False),
        sa.Column("verification_status", sa.String(length=30), nullable=False),
        sa.Column(
            "training_eligible",
            sa.Boolean(),
            server_default=sa.false(),
            nullable=False,
        ),
        sa.Column("final_value_json", sa.JSON(), nullable=False),
        sa.Column("changed_fields_json", sa.JSON(), nullable=False),
        sa.Column("idempotency_key", sa.String(length=120), nullable=False),
        sa.Column("content_fingerprint", sa.String(length=71), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.CheckConstraint(
            "feedback_type IN ('accepted', 'edited', 'rejected', 'ignored')",
            name="ck_ai_decision_feedback_type",
        ),
        sa.CheckConstraint(
            "verification_status IN ('client_observed', 'server_verified', "
            "'human_verified', 'invalidated')",
            name="ck_ai_decision_feedback_verification",
        ),
        sa.CheckConstraint(
            "NOT training_eligible OR verification_status IN "
            "('server_verified', 'human_verified')",
            name="ck_ai_decision_feedback_training_eligibility",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "decision_id"],
            ["ai_decisions.tenant_id", "ai_decisions.id"],
            name="fk_ai_decision_feedback_tenant_decision",
            ondelete="RESTRICT",
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_ai_decision_feedback_tenant_idempotency",
        ),
    )
    op.create_index(
        "ix_ai_decision_feedback_tenant_decision_time",
        "ai_decision_feedback",
        ["tenant_id", "decision_id", "created_at"],
    )
    op.create_index(
        "ix_ai_decision_feedback_tenant_type_time",
        "ai_decision_feedback",
        ["tenant_id", "feedback_type", "created_at"],
    )
    op.create_index(
        "ix_ai_decision_feedback_expense_claim_id",
        "ai_decision_feedback",
        ["expense_claim_id"],
    )
    op.create_index(
        "ix_ai_decision_feedback_correlation_id",
        "ai_decision_feedback",
        ["correlation_id"],
    )

    op.create_table(
        "workflow_outcomes",
        sa.Column("id", sa.String(length=36), nullable=False),
        sa.Column("tenant_id", sa.String(length=64), nullable=False),
        sa.Column("expense_case_id", sa.String(length=36), nullable=False),
        sa.Column("decision_id", sa.String(length=36), nullable=False),
        sa.Column("business_event_id", sa.String(length=36), nullable=True),
        sa.Column("expense_claim_id", sa.String(length=36), nullable=False),
        sa.Column("correlation_id", sa.String(length=64), nullable=False),
        sa.Column("outcome_type", sa.String(length=50), nullable=False),
        sa.Column("outcome_status", sa.String(length=20), nullable=False),
        sa.Column("actor_id", sa.String(length=120), nullable=False),
        sa.Column("actor_type", sa.String(length=30), nullable=False),
        sa.Column("result_json", sa.JSON(), nullable=False),
        sa.Column("idempotency_key", sa.String(length=120), nullable=False),
        sa.Column("content_fingerprint", sa.String(length=71), nullable=False),
        sa.Column(
            "effective_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.func.now(),
            nullable=False,
        ),
        sa.CheckConstraint(
            "outcome_status IN ('recorded', 'verified', 'reversed')",
            name="ck_workflow_outcomes_status",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "expense_case_id", "business_event_id"],
            [
                "business_events.tenant_id",
                "business_events.expense_case_id",
                "business_events.id",
            ],
            name="fk_workflow_outcomes_tenant_event",
            ondelete="RESTRICT",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "expense_case_id", "decision_id"],
            [
                "ai_decisions.tenant_id",
                "ai_decisions.expense_case_id",
                "ai_decisions.id",
            ],
            name="fk_workflow_outcomes_tenant_decision",
            ondelete="RESTRICT",
        ),
        sa.ForeignKeyConstraint(
            ["tenant_id", "expense_case_id"],
            ["expense_cases.tenant_id", "expense_cases.id"],
            name="fk_workflow_outcomes_tenant_case",
            ondelete="RESTRICT",
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "tenant_id",
            "idempotency_key",
            name="uq_workflow_outcomes_tenant_idempotency",
        ),
    )
    op.create_index(
        "ix_workflow_outcomes_tenant_case_time",
        "workflow_outcomes",
        ["tenant_id", "expense_case_id", "effective_at"],
    )
    op.create_index(
        "ix_workflow_outcomes_tenant_type_time",
        "workflow_outcomes",
        ["tenant_id", "outcome_type", "effective_at"],
    )
    op.create_index(
        "ix_workflow_outcomes_expense_claim_id",
        "workflow_outcomes",
        ["expense_claim_id"],
    )
    op.create_index(
        "ix_workflow_outcomes_correlation_id",
        "workflow_outcomes",
        ["correlation_id"],
    )


def downgrade() -> None:
    op.drop_index("ix_workflow_outcomes_correlation_id", table_name="workflow_outcomes")
    op.drop_index("ix_workflow_outcomes_expense_claim_id", table_name="workflow_outcomes")
    op.drop_index("ix_workflow_outcomes_tenant_type_time", table_name="workflow_outcomes")
    op.drop_index("ix_workflow_outcomes_tenant_case_time", table_name="workflow_outcomes")
    op.drop_table("workflow_outcomes")

    op.drop_index("ix_ai_decision_feedback_correlation_id", table_name="ai_decision_feedback")
    op.drop_index("ix_ai_decision_feedback_expense_claim_id", table_name="ai_decision_feedback")
    op.drop_index("ix_ai_decision_feedback_tenant_type_time", table_name="ai_decision_feedback")
    op.drop_index("ix_ai_decision_feedback_tenant_decision_time", table_name="ai_decision_feedback")
    op.drop_table("ai_decision_feedback")

    op.drop_index("ix_ai_decisions_correlation_id", table_name="ai_decisions")
    op.drop_index("ix_ai_decisions_agent_run_id", table_name="ai_decisions")
    op.drop_index("ix_ai_decisions_expense_claim_id", table_name="ai_decisions")
    op.drop_index("ix_ai_decisions_tenant_subject", table_name="ai_decisions")
    op.drop_index("ix_ai_decisions_tenant_case_time", table_name="ai_decisions")
    op.drop_table("ai_decisions")

    op.drop_constraint(
        "uq_business_events_tenant_case_id",
        "business_events",
        type_="unique",
    )
    op.drop_constraint("uq_expense_cases_tenant_id", "expense_cases", type_="unique")
