"""log retention, storage snapshots and audit indexes

Revision ID: 0009_logs_storage
Revises: 0008_unique_kb_node
"""
from alembic import context, op
import sqlalchemy as sa

revision = "0009_logs_storage"
down_revision = "0008_unique_kb_node"
branch_labels = None
depends_on = None


def upgrade() -> None:
    inspector = None if context.is_offline_mode() else sa.inspect(op.get_bind())
    tables = set() if inspector is None else set(inspector.get_table_names())
    if "sys_log_retention_policy" not in tables:
        op.create_table(
        "sys_log_retention_policy",
        sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
        sa.Column("retention_days", sa.Integer(), nullable=True),
        sa.Column("enabled", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("last_run_at", sa.DateTime(), nullable=True),
        sa.Column("last_result", sa.Text(), nullable=True),
        sa.Column("updated_by", sa.BigInteger(), nullable=True),
        sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    if "sys_storage_snapshot" not in tables:
        op.create_table(
        "sys_storage_snapshot",
        sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True),
        sa.Column("scope", sa.String(50), nullable=False),
        sa.Column("total_bytes", sa.BigInteger(), nullable=True),
        sa.Column("detail_json", sa.Text(), nullable=False),
        sa.Column("status", sa.String(20), nullable=False),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    _create_index_if_missing("sys_knowledge_retrieval_log", "ix_retrieval_status_created", ["status", "created_at"])
    _create_index_if_missing("sys_knowledge_retrieval_log", "ix_retrieval_created_id", ["created_at", "id"])
    _create_index_if_missing("sys_ai_request_log", "ix_ai_log_status_created", ["status", "created_at"])
    _create_index_if_missing("sys_operation_log", "ix_operation_module_created", ["module", "created_at"])
    _create_index_if_missing("sys_chat_session", "ix_chat_session_deleted_updated", ["is_deleted", "updated_at"])


def _create_index_if_missing(table: str, name: str, columns: list[str]) -> None:
    indexes = set() if context.is_offline_mode() else {
        item["name"] for item in sa.inspect(op.get_bind()).get_indexes(table)
    }
    if name not in indexes:
        op.create_index(name, table, columns)


def downgrade() -> None:
    op.drop_index("ix_chat_session_deleted_updated", table_name="sys_chat_session")
    op.drop_index("ix_operation_module_created", table_name="sys_operation_log")
    op.drop_index("ix_ai_log_status_created", table_name="sys_ai_request_log")
    op.drop_index("ix_retrieval_created_id", table_name="sys_knowledge_retrieval_log")
    op.drop_index("ix_retrieval_status_created", table_name="sys_knowledge_retrieval_log")
    op.drop_table("sys_storage_snapshot")
    op.drop_table("sys_log_retention_policy")
