"""task run logs

Revision ID: 065_task_run_logs
Revises: 064_agent_lifecycle
Create Date: 2026-06-21
"""

import sqlalchemy as sa
from alembic import op


revision = "065_task_run_logs"
down_revision = "064_agent_lifecycle"
branch_labels = None
depends_on = None


def _tables(bind) -> set[str]:
    return set(sa.inspect(bind).get_table_names())


def _index_names(bind, table_name: str) -> set[str]:
    return {index["name"] for index in sa.inspect(bind).get_indexes(table_name)}


def _create_index_if_missing(table: str, index_name: str, columns: list[str]) -> None:
    bind = op.get_bind()
    if table in _tables(bind) and index_name not in _index_names(bind, table):
        op.create_index(index_name, table, columns)


def upgrade() -> None:
    bind = op.get_bind()
    if "task_run_logs" not in _tables(bind):
        op.create_table(
            "task_run_logs",
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("task_key", sa.String(length=80), nullable=False),
            sa.Column("task_name", sa.String(length=120), nullable=False),
            sa.Column("trigger_type", sa.String(length=24), nullable=False),
            sa.Column("status", sa.String(length=24), nullable=False),
            sa.Column("operator_id", sa.BigInteger(), nullable=True),
            sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
            sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("duration_ms", sa.Integer(), nullable=True),
            sa.Column("summary", sa.JSON(), nullable=True),
            sa.Column("error_message", sa.Text(), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.PrimaryKeyConstraint("id"),
        )

    _create_index_if_missing("task_run_logs", "ix_task_run_logs_task_key", ["task_key"])
    _create_index_if_missing("task_run_logs", "ix_task_run_logs_trigger_type", ["trigger_type"])
    _create_index_if_missing("task_run_logs", "ix_task_run_logs_status", ["status"])
    _create_index_if_missing("task_run_logs", "ix_task_run_logs_operator_id", ["operator_id"])
    _create_index_if_missing("task_run_logs", "ix_task_run_logs_started_at", ["started_at"])


def downgrade() -> None:
    bind = op.get_bind()
    if "task_run_logs" in _tables(bind):
        op.drop_table("task_run_logs")
