"""add testing generation history table

Revision ID: c9f6e7a1bd34
Revises: b7217f0c3d92
Create Date: 2026-04-26 20:30:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = "c9f6e7a1bd34"
down_revision: Union[str, None] = "b7217f0c3d92"
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:
    table_name = "testing_generations"
    inspector = sa.inspect(op.get_bind())
    if table_name not in inspector.get_table_names():
        return
    existing_indexes = {item["name"] for item in inspector.get_indexes(table_name)}
    for index_name in [
        op.f("ix_testing_generations_knowledge_base_id"),
        op.f("ix_testing_generations_source_job_id"),
        op.f("ix_testing_generations_id"),
    ]:
        if index_name in existing_indexes:
            op.drop_index(index_name, table_name=table_name)
    op.drop_table(table_name)
