# Copyright 2026 Flower Labs GmbH. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Initialize migration of state tables.

Revision ID: 8e65d8ae60b0
Revises:
Create Date: 2026-01-28 11:03:18.038794
"""
from collections.abc import Sequence

import sqlalchemy as sa
from alembic import op

# pylint: disable=no-member

# revision identifiers, used by Alembic.
revision: str = "8e65d8ae60b0"
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Upgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    # LinkState tables
    op.create_table(
        "node",
        sa.Column("node_id", sa.Integer(), nullable=True),
        sa.Column("owner_aid", sa.String(), nullable=True),
        sa.Column("owner_name", sa.String(), nullable=True),
        sa.Column("status", sa.String(), nullable=True),
        sa.Column("registered_at", sa.String(), nullable=True),
        sa.Column("last_activated_at", sa.String(), nullable=True),
        sa.Column("last_deactivated_at", sa.String(), nullable=True),
        sa.Column("unregistered_at", sa.String(), nullable=True),
        sa.Column("online_until", sa.TIMESTAMP(), nullable=True),
        sa.Column("heartbeat_interval", sa.Float(), nullable=True),
        sa.Column("public_key", sa.LargeBinary(), nullable=True),
        sa.UniqueConstraint("node_id"),
        sa.UniqueConstraint("public_key"),
    )
    op.create_index("idx_node_owner_aid", "node", ["owner_aid"], unique=False)
    op.create_index("idx_node_status", "node", ["status"], unique=False)
    op.create_index("idx_online_until", "node", ["online_until"], unique=False)
    op.create_table(
        "run",
        sa.Column("run_id", sa.Integer(), nullable=True),
        sa.Column("fab_id", sa.String(), nullable=True),
        sa.Column("fab_version", sa.String(), nullable=True),
        sa.Column("fab_hash", sa.String(), nullable=True),
        sa.Column("override_config", sa.String(), nullable=True),
        sa.Column("pending_at", sa.String(), nullable=True),
        sa.Column("starting_at", sa.String(), nullable=True),
        sa.Column("running_at", sa.String(), nullable=True),
        sa.Column("finished_at", sa.String(), nullable=True),
        sa.Column("sub_status", sa.String(), nullable=True),
        sa.Column("details", sa.String(), nullable=True),
        sa.Column("federation", sa.String(), nullable=True),
        sa.Column("federation_options", sa.LargeBinary(), nullable=True),
        sa.Column("flwr_aid", sa.String(), nullable=True),
        sa.Column("bytes_sent", sa.Integer(), server_default="0", nullable=True),
        sa.Column("bytes_recv", sa.Integer(), server_default="0", nullable=True),
        sa.Column("clientapp_runtime", sa.Float(), server_default="0.0", nullable=True),
        sa.UniqueConstraint("run_id"),
    )
    op.create_table(
        "logs",
        sa.Column("timestamp", sa.Float(), nullable=True),
        sa.Column("run_id", sa.Integer(), nullable=True),
        sa.Column("node_id", sa.Integer(), nullable=True),
        sa.Column("log", sa.String(), nullable=True),
        sa.ForeignKeyConstraint(
            ["run_id"],
            ["run.run_id"],
        ),
        sa.UniqueConstraint("timestamp", "run_id", "node_id"),
    )
    op.create_table(
        "context",
        sa.Column("run_id", sa.Integer(), nullable=True),
        sa.Column("context", sa.LargeBinary(), nullable=True),
        sa.ForeignKeyConstraint(
            ["run_id"],
            ["run.run_id"],
        ),
        sa.UniqueConstraint("run_id"),
    )
    op.create_table(
        "message_ins",
        sa.Column("message_id", sa.String(), nullable=True),
        sa.Column("group_id", sa.String(), nullable=True),
        sa.Column("run_id", sa.Integer(), nullable=True),
        sa.Column("src_node_id", sa.Integer(), nullable=True),
        sa.Column("dst_node_id", sa.Integer(), nullable=True),
        sa.Column("reply_to_message_id", sa.String(), nullable=True),
        sa.Column("created_at", sa.Float(), nullable=True),
        sa.Column("delivered_at", sa.String(), nullable=True),
        sa.Column("ttl", sa.Float(), nullable=True),
        sa.Column("message_type", sa.String(), nullable=True),
        sa.Column("content", sa.LargeBinary(), nullable=True),
        sa.Column("error", sa.LargeBinary(), nullable=True),
        sa.ForeignKeyConstraint(
            ["run_id"],
            ["run.run_id"],
        ),
        sa.UniqueConstraint("message_id"),
    )
    op.create_table(
        "message_res",
        sa.Column("message_id", sa.String(), nullable=True),
        sa.Column("group_id", sa.String(), nullable=True),
        sa.Column("run_id", sa.Integer(), nullable=True),
        sa.Column("src_node_id", sa.Integer(), nullable=True),
        sa.Column("dst_node_id", sa.Integer(), nullable=True),
        sa.Column("reply_to_message_id", sa.String(), nullable=True),
        sa.Column("created_at", sa.Float(), nullable=True),
        sa.Column("delivered_at", sa.String(), nullable=True),
        sa.Column("ttl", sa.Float(), nullable=True),
        sa.Column("message_type", sa.String(), nullable=True),
        sa.Column("content", sa.LargeBinary(), nullable=True),
        sa.Column("error", sa.LargeBinary(), nullable=True),
        sa.ForeignKeyConstraint(
            ["run_id"],
            ["run.run_id"],
        ),
        sa.UniqueConstraint("message_id"),
    )
    # CoreState tables
    op.create_table(
        "token_store",
        sa.Column("run_id", sa.Integer(), nullable=True),
        sa.Column("token", sa.String(), nullable=False),
        sa.Column("active_until", sa.Float(), nullable=True),
        sa.PrimaryKeyConstraint("run_id"),
        sa.UniqueConstraint("token"),
    )
    # ObjectStore tables
    op.create_table(
        "objects",
        sa.Column("object_id", sa.String(), nullable=True),
        sa.Column("content", sa.LargeBinary(), nullable=True),
        sa.Column("is_available", sa.Integer(), server_default="0", nullable=False),
        sa.Column("ref_count", sa.Integer(), server_default="0", nullable=False),
        sa.CheckConstraint("is_available IN (0, 1)", name="ck_objects_is_available"),
        sa.PrimaryKeyConstraint("object_id"),
    )
    op.create_table(
        "object_children",
        sa.Column("parent_id", sa.String(), nullable=False),
        sa.Column("child_id", sa.String(), nullable=False),
        sa.ForeignKeyConstraint(
            ["child_id"], ["objects.object_id"], ondelete="CASCADE"
        ),
        sa.ForeignKeyConstraint(
            ["parent_id"], ["objects.object_id"], ondelete="CASCADE"
        ),
        sa.PrimaryKeyConstraint("parent_id", "child_id"),
    )
    op.create_table(
        "run_objects",
        sa.Column("run_id", sa.Integer(), nullable=False),
        sa.Column("object_id", sa.String(), nullable=False),
        sa.ForeignKeyConstraint(
            ["object_id"], ["objects.object_id"], ondelete="CASCADE"
        ),
        sa.PrimaryKeyConstraint("run_id", "object_id"),
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    """Downgrade schema."""
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("run_objects")
    op.drop_table("object_children")
    op.drop_table("objects")
    op.drop_table("token_store")
    op.drop_table("message_res")
    op.drop_table("message_ins")
    op.drop_table("context")
    op.drop_table("logs")
    op.drop_table("run")
    op.drop_index("idx_online_until", table_name="node")
    op.drop_index("idx_node_status", table_name="node")
    op.drop_index("idx_node_owner_aid", table_name="node")
    op.drop_table("node")
    # ### end Alembic commands ###
