"""repair testing generations table

Revision ID: f0a1b2c3d4e5
Revises: e9b1b3d7a4c9
Create Date: 2026-05-16 10:05:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "f0a1b2c3d4e5"
down_revision: Union[str, None] = "e9b1b3d7a4c9"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _ensure_index(table_name: str, index_name: str, columns: list[str]) -> None:
    inspector = sa.inspect(op.get_bind())
    existing_indexes = {item["name"] for item in inspector.get_indexes(table_name)}
    if index_name not in existing_indexes:
        op.create_index(index_name, table_name, columns, unique=False)


def upgrade() -> None:
    table_name = "testing_generations"
    inspector = sa.inspect(op.get_bind())
    if table_name not in inspector.get_table_names():
        op.create_table(
            table_name,
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("job_id", sa.Integer(), nullable=False),
            sa.Column("source_job_id", sa.Integer(), nullable=True),
            sa.Column("source_document_name", sa.String(length=255), nullable=False),
            sa.Column("generated_at", sa.DateTime(), nullable=False),
            sa.Column("total_requirements", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("knowledge_base_id", sa.Integer(), nullable=True),
            sa.Column("generated_file", sa.JSON(), nullable=False),
            sa.Column("created_at", sa.DateTime(), nullable=False),
            sa.Column("updated_at", sa.DateTime(), nullable=False),
            sa.ForeignKeyConstraint(["job_id"], ["tool_jobs.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["knowledge_base_id"], ["knowledge_bases.id"]),
            sa.ForeignKeyConstraint(["source_job_id"], ["tool_jobs.id"]),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("job_id"),
        )

    _ensure_index(table_name, op.f("ix_testing_generations_id"), ["id"])
    _ensure_index(table_name, op.f("ix_testing_generations_source_job_id"), ["source_job_id"])
    _ensure_index(table_name, op.f("ix_testing_generations_knowledge_base_id"), ["knowledge_base_id"])


def downgrade() -> None:
    # Repair migration: keep existing data and schema intact on downgrade.
    pass
