"""Doris warehouse migrations — all warehouse tables (consolidated first deployment).

Creates 8 Doris warehouse tables with the complete schema from all accumulated
changes (translated_text, analyzed metrics, pipeline_errors, column renames).
Suitable for first-time deployment — no incremental migration history needed.
"""

from __future__ import annotations

from repo_core.migrations.builder import MigrationBuilder
from repo_core.migrations.runner import Migration

# ---------------------------------------------------------------------------
# Doris (warehouse) migrations
# ---------------------------------------------------------------------------


def get_doris_migrations() -> list[Migration]:
    """Return ordered Doris warehouse migrations.

    Only models with ``_warehouse_include`` are registered here.
    """
    return [
        # ------------------------------------------------------------------ #
        # Telegram messages warehouse                                          #
        # ------------------------------------------------------------------ #
        Migration(
            version="tg_message_doris_0001",
            description="Create telegram_messages warehouse table (v3: DATETIME columns)",
            dialect="doris",
            up=(
                MigrationBuilder("telegram_messages", dialect="doris")
                .bigint("peer_id", nullable=False)
                .bigint("message_id", nullable=False)
                .timestamp("message_sent_at", nullable=False)
                .text("message", nullable=True)
                .boolean("out", nullable=True)
                .boolean("mentioned", nullable=True)
                .boolean("media_unread", nullable=True)
                .boolean("silent", nullable=True)
                .boolean("post", nullable=True)
                .boolean("from_scheduled", nullable=True)
                .boolean("legacy", nullable=True)
                .boolean("edit_hide", nullable=True)
                .boolean("pinned", nullable=True)
                .boolean("noforwards", nullable=True)
                .boolean("invert_media", nullable=True)
                .boolean("offline", nullable=True)
                .boolean("paid_suggested_post_stars", nullable=True)
                .boolean("paid_suggested_post_ton", nullable=True)
                .jsonb("from_id", nullable=True)
                .bigint("from_boosts_applied", nullable=True)
                .jsonb("saved_peer_id", nullable=True)
                .jsonb("fwd_from", nullable=True)
                .bigint("via_bot_id", nullable=True)
                .bigint("via_business_bot_id", nullable=True)
                .jsonb("reply_to", nullable=True)
                .jsonb("media", nullable=True)
                .jsonb("reply_markup", nullable=True)
                .jsonb("details", nullable=True)
                .bigint("views", nullable=True)
                .bigint("forwards", nullable=True)
                .jsonb("replies", nullable=True)
                .timestamp("edit_date", nullable=True)
                .text("post_author", nullable=True)
                .bigint("grouped_id", nullable=True)
                .jsonb("reactions", nullable=True)
                .jsonb("restriction_reason", nullable=True)
                .bigint("ttl_period", nullable=True)
                .bigint("quick_reply_shortcut_id", nullable=True)
                .jsonb("effect", nullable=True)
                .jsonb("factcheck", nullable=True)
                .timestamp("report_delivery_until_date", nullable=True)
                .bigint("paid_message_stars", nullable=True)
                .jsonb("suggested_post", nullable=True)
                .timestamp("crawled_at", nullable=True)
                .timestamp("created_at", nullable=True)
                .timestamp("updated_at", nullable=True)
                .doris_unique_key(["peer_id", "message_id"])
                .doris_distributed_by("peer_id", buckets=32)
                .create_table()
            ),
            down=MigrationBuilder("telegram_messages", dialect="doris").drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Crawler metrics warehouse                                            #
        # ------------------------------------------------------------------ #
        Migration(
            version="crawl_metric_doris_0002",
            description="Create telegram_crawl_metrics warehouse table (v2: peer_id + message_id unique key)",
            dialect="doris",
            up=(
                MigrationBuilder("telegram_crawl_metrics", dialect="doris")
                .bigint("peer_id", nullable=False)
                .bigint("message_id", nullable=False)
                .uuid("account_id", nullable=True)
                .text("proxy_id", nullable=True)
                .timestamp("message_sent_at", nullable=False)
                .varchar("status", 32, nullable=False)
                .timestamp("ingested_at", nullable=False)
                .timestamp("persisted_at", nullable=True)
                .timestamp("parsed_at", nullable=True)
                .bigint("parse_duration", nullable=True)
                .timestamp("analyzed_at", nullable=True)
                .bigint("analyze_duration", nullable=True)
                .timestamp("created_at", nullable=True, default="now()")
                .doris_unique_key(["peer_id", "message_id"])
                .doris_distributed_by("peer_id", buckets=32)
                .create_table()
            ),
            down=MigrationBuilder(
                "telegram_crawl_metrics", dialect="doris"
            ).drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Crawler events warehouse                                             #
        # ------------------------------------------------------------------ #
        Migration(
            version="crawler_event_doris_0001",
            description="Create telegram_crawler_events warehouse table",
            dialect="doris",
            up=(
                MigrationBuilder("telegram_crawler_events", dialect="doris")
                .uuid("id")
                .uuid("account_id", nullable=True)
                .text("proxy_id", nullable=True)
                .text("crawler_instance_id", nullable=False)
                .text("event_type", nullable=False)
                .jsonb("event_data", nullable=True)
                .timestamp("created_at", nullable=True, default="now()")
                .doris_unique_key(["id"])
                .doris_distributed_by("id", buckets=10)
                .create_table()
            ),
            down=MigrationBuilder(
                "telegram_crawler_events", dialect="doris"
            ).drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Telegram parsed messages warehouse                                       #
        # ------------------------------------------------------------------ #
        Migration(
            version="telegram_parsed_msg_doris_0001",
            description="Create telegram_parsed_messages warehouse table (v2: DATETIME columns)",
            dialect="doris",
            up=(
                MigrationBuilder("telegram_parsed_messages", dialect="doris")
                .bigint("peer_id", nullable=False)
                .bigint("message_id", nullable=False)
                .timestamp("message_sent_at", nullable=False)
                .bigint("from_id", nullable=True)
                .boolean("from_type", nullable=True)
                .text("message_text", nullable=True)
                .varchar("message_lang", 8, nullable=True)
                .integer("views", nullable=False, default=0)
                .integer("forwards_count", nullable=False, default=0)
                .integer("reply_count", nullable=False, default=0)
                .boolean("has_media", nullable=False, default=0)
                .varchar("media_type", 20, nullable=True)
                .boolean("is_forward", nullable=False, default=0)
                .bigint("fwd_from_peer_id", nullable=True)
                .bigint("fwd_from_msg_id", nullable=True)
                .timestamp("fwd_from_date", nullable=True)
                .bigint("reply_to_msg_id", nullable=True)
                .timestamp("edit_date", nullable=True)
                .text("translated_text", nullable=True)
                .timestamp("crawled_at", nullable=False)
                .timestamp("created_at", nullable=False)
                .timestamp("updated_at", nullable=False)
                .doris_unique_key(["peer_id", "message_id", "message_sent_at"])
                .doris_partition_by_range("message_sent_at")
                .doris_distributed_by("peer_id", buckets=32)
                .doris_properties(
                    {
                        "replication_num": "1",
                        "enable_unique_key_merge_on_write": "true",
                        "dynamic_partition.enable": "true",
                        "dynamic_partition.time_unit": "DAY",
                        "dynamic_partition.end": "1",
                        "dynamic_partition.prefix": "p",
                    }
                )
                .create_table()
            ),
            down=MigrationBuilder(
                "telegram_parsed_messages", dialect="doris"
            ).drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Message reactions warehouse                                          #
        # ------------------------------------------------------------------ #
        Migration(
            version="msg_reactions_doris_0001",
            description="Create message_reactions warehouse table",
            dialect="doris",
            up=(
                MigrationBuilder("message_reactions", dialect="doris")
                .bigint("peer_id", nullable=False)
                .bigint("message_id", nullable=False)
                .varchar("emoticon", 16, nullable=False)
                .integer("reaction_count", nullable=False, default=0)
                .boolean("is_custom", nullable=False, default=0)
                .timestamp("updated_at", nullable=False)
                .doris_unique_key(["peer_id", "message_id", "emoticon"])
                .doris_distributed_by("peer_id", buckets=32)
                .doris_properties(
                    {
                        "replication_num": "1",
                        "enable_unique_key_merge_on_write": "true",
                    }
                )
                .create_table()
            ),
            down=MigrationBuilder("message_reactions", dialect="doris").drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Message details warehouse (renamed from message_entities)              #
        # ------------------------------------------------------------------ #
        Migration(
            version="msg_details_doris_0001",
            description="Create telegram_message_details warehouse table",
            dialect="doris",
            up=(
                MigrationBuilder("telegram_message_details", dialect="doris")
                .bigint("peer_id", nullable=False)
                .bigint("message_id", nullable=False)
                .varchar("detail_type", 32, nullable=False)
                .text("detail_value", nullable=True)
                .integer("offset", nullable=False)
                .integer("length", nullable=False)
                .doris_duplicate_key(["peer_id", "message_id"])
                .doris_distributed_by("peer_id", buckets=32)
                .create_table()
            ),
            down=MigrationBuilder(
                "telegram_message_details", dialect="doris"
            ).drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Pipeline errors warehouse                                             #
        # ------------------------------------------------------------------ #
        Migration(
            version="pipeline_errors_doris_0001",
            description="Create pipeline_errors warehouse table",
            dialect="doris",
            up=(
                MigrationBuilder("pipeline_errors", dialect="doris")
                # -- Primary key -------------------------------------------
                .uuid("id", nullable=False)
                # -- Classification ----------------------------------------
                .varchar("error_category", 64, nullable=False)
                .varchar("severity", 32, nullable=False)
                # -- Attribution -------------------------------------------
                .varchar("source_service", 64, nullable=False)
                .varchar("source_topic", 128, nullable=False)
                .integer("source_partition", nullable=True)
                .bigint("source_offset", nullable=True)
                # -- What failed ------------------------------------------
                .varchar("target_topic", 128, nullable=True)
                .varchar("target_operation", 64, nullable=True)
                # -- Original message identity -----------------------------
                .bigint("telegram_message_id", nullable=True)
                .bigint("peer_id", nullable=True)
                .uuid("account_id", nullable=True)
                .varchar("proxy_id", 64, nullable=True)
                # -- Error details ----------------------------------------
                .text("error_message", nullable=False)
                .varchar("error_type", 128, nullable=False)
                .text("error_traceback", nullable=True)
                # -- Input message ----------------------------------------
                .text("payload_preview", nullable=True)
                .jsonb("full_payload", nullable=True)
                .boolean("payload_truncated", nullable=False, default=0)
                .integer("payload_size_bytes", nullable=True)
                # -- Retry state ------------------------------------------
                .boolean("is_retryable", nullable=False, default=1)
                .integer("retry_count", nullable=False, default=0)
                .integer("max_retries", nullable=False, default=3)
                # -- Timestamps -------------------------------------------
                .timestamp("occurred_at", nullable=False)
                .timestamp("created_at", nullable=True)
                # -- Doris storage engine settings ------------------------
                .doris_unique_key(["id"])
                .doris_distributed_by("id", buckets=10)
                .create_table()
            ),
            down=MigrationBuilder("pipeline_errors", dialect="doris").drop_table(),
        ),
        # ------------------------------------------------------------------ #
        # Telegram channels warehouse                                             #
        # ------------------------------------------------------------------ #
        Migration(
            version="telegram_channels_doris_0005",
            description="Create telegram_channels warehouse table for analytics JOINs",
            dialect="doris",
            up=(
                MigrationBuilder("telegram_channels", dialect="doris")
                .bigint("channel_id", nullable=False)
                .varchar("title", 500, nullable=False)
                .varchar("username", 200, nullable=True)
                .varchar("kind", 50, nullable=True, default="channel")
                .bigint("member_count", nullable=True)
                .text("description", nullable=True)
                .uuid("account_id", nullable=True)
                .timestamp("assigned_at", nullable=True)
                .timestamp("created_at", nullable=True)
                .timestamp("updated_at", nullable=True)
                .doris_unique_key(["channel_id"])
                .doris_distributed_by("channel_id", buckets=10)
                .create_table()
            ),
            down=MigrationBuilder("telegram_channels", dialect="doris").drop_table(),
        ),
    ]
