"""bootstrap model-owned and legacy application tables for empty databases

Revision ID: 20260803_11a
Revises: 20260803_11
Create Date: 2026-08-11
"""

from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

from supply_infra.db.base import Base
import supply_infra.db.models  # noqa: F401

revision: str = "20260803_11a"
down_revision: str | None = "20260803_11"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create model tables that historical deployments supplied outside Alembic."""
    model_tables = [
        table
        for name, table in Base.metadata.tables.items()
        if not name.startswith("find_agent_v2_")
    ]
    Base.metadata.create_all(bind=op.get_bind(), tables=model_tables, checkfirst=True)

    if "global_category" not in sa.inspect(op.get_bind()).get_table_names():
        op.create_table(
            "global_category",
            sa.Column("id", sa.BigInteger(), autoincrement=True, nullable=False),
            sa.Column("name", sa.String(128), nullable=True, comment="名称"),
            sa.Column("description", sa.Text(), nullable=True, comment="描述"),
            sa.Column("level", sa.Integer(), nullable=True, comment="层级"),
            sa.Column("parent_id", sa.BigInteger(), nullable=True, comment="父节点"),
            sa.Column("source_id", sa.BigInteger(), nullable=False, comment="hive表stable_id"),
            sa.Column("source_parent_id", sa.BigInteger(), nullable=False, comment="hive表父stable_id"),
            sa.Column("is_delete", sa.Integer(), server_default="0", nullable=False, comment="是否删除0-正常 1-删除"),
            sa.Column("create_time", sa.DateTime(), server_default=sa.func.now(), nullable=True, comment="创建时间"),
            sa.Column("update_time", sa.DateTime(), server_default=sa.func.now(), nullable=False, comment="更新时间"),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("source_id", name="uk_source_id"),
            mysql_charset="utf8mb4",
            mysql_collate="utf8mb4_unicode_ci",
            comment="全局分类 — 从 ODPS loghubods.global_category 同步",
        )
        op.create_index("idx_global_category_parent_id", "global_category", ["parent_id"])
        op.create_index("idx_global_category_level", "global_category", ["level"])
        op.execute("ALTER TABLE global_category MODIFY update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")


def downgrade() -> None:
    # Adoption is forward-only because existing deployments can own these tables.
    pass
