#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
"""create initial database schema for ops v0.1.2

Revision ID: 80f110f929fc
Revises:
Create Date: 2026-01-20 21:00:48.235109

"""

from typing import Sequence, Union

from alembic import op
from openjiuwen_studio.core.database.migration_utils import table_exists, column_exists, index_exists
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
from sqlalchemy import inspect

# revision identifiers, used by Alembic.
revision: str = "80f110f929fc"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    if not table_exists("job_user_draft"):
        op.create_table(
            "job_user_draft",
            sa.Column(
                "id", sa.BigInteger(), autoincrement=True, nullable=False, comment="主键ID"
            ),
            sa.Column("space_id", sa.String(length=128), nullable=False, comment="空间ID"),
            sa.Column("user_id", sa.String(length=128), nullable=False, comment="用户ID"),
            sa.Column("name", sa.String(length=64), nullable=True, comment="任务名称"),
            sa.Column("desc", sa.String(length=256), nullable=True, comment="任务描述"),
            sa.Column("rawTemplates", sa.Text(), nullable=True, comment="原始模板信息"),
            sa.Column(
                "optimizeInfo", mysql.MEDIUMTEXT(), nullable=True, comment="优化配置"
            ),
            sa.Column("modelInfo", sa.Text(), nullable=True, comment="调优大模型配置"),
            sa.Column("assistantInfo", sa.Text(), nullable=True, comment="调优大模型配置"),
            sa.Column("agentTools", sa.Text(), nullable=True, comment="调优工具"),
            sa.Column(
                "is_deleted",
                sa.Integer(),
                nullable=False,
                comment="草稿是否删除，1 删除 0 有效",
            ),
            sa.Column("created_at", sa.DateTime(), nullable=False, comment="创建时间"),
            sa.Column("updated_at", sa.DateTime(), nullable=False, comment="更新时间"),
            sa.PrimaryKeyConstraint("id"),
        )

    if not table_exists("job_user_info"):
        op.create_table(
            "job_user_info",
            sa.Column(
                "id", sa.BigInteger(), autoincrement=True, nullable=False, comment="主键ID"
            ),
            sa.Column("job_id", sa.String(length=128), nullable=False, comment="任务ID"),
            sa.Column("space_id", sa.String(length=128), nullable=False, comment="空间ID"),
            sa.Column("user_id", sa.String(length=128), nullable=False, comment="用户ID"),
            sa.Column("name", sa.String(length=64), nullable=True, comment="任务名称"),
            sa.Column("desc", sa.String(length=256), nullable=True, comment="任务描述"),
            sa.Column("rawTemplates", sa.Text(), nullable=True, comment="原prompt信息"),
            sa.Column("bestTemplates", sa.Text(), nullable=True, comment="最优prompt信息"),
            sa.Column("bestIteration", sa.Integer(), nullable=True, comment="最优迭代轮数"),
            sa.Column(
                "timeCost", sa.Integer(), nullable=True, comment="任务时间消耗，单位秒"
            ),
            sa.Column("history", sa.JSON(), nullable=True, comment="历史记录信息"),
            sa.Column(
                "success_rate",
                sa.DECIMAL(precision=5, scale=4),
                nullable=True,
                comment="最优任务成功率",
            ),
            sa.Column(
                "progress_rate",
                sa.DECIMAL(precision=5, scale=4),
                nullable=True,
                comment="任务进展",
            ),
            sa.Column(
                "optimizeInfo", mysql.MEDIUMTEXT(), nullable=True, comment="优化配置"
            ),
            sa.Column("modelInfo", sa.Text(), nullable=True, comment="调优大模型配置"),
            sa.Column("assistantInfo", sa.Text(), nullable=True, comment="助手模型配置"),
            sa.Column("agentTools", sa.Text(), nullable=True, comment="调优工具"),
            sa.Column(
                "status",
                sa.String(length=64),
                nullable=True,
                comment="任务状态：running finished failed",
            ),
            sa.Column("errorMsg", sa.Text(), nullable=True, comment="任务报错信息"),
            sa.Column(
                "is_deleted",
                sa.Integer(),
                nullable=False,
                comment="是否删除，1 删除 0 有效",
            ),
            sa.Column("created_at", sa.DateTime(), nullable=False, comment="创建时间"),
            sa.Column("updated_at", sa.DateTime(), nullable=False, comment="更新时间"),
            sa.PrimaryKeyConstraint("id"),
        )

    if not table_exists("prompt_basic"):
        op.create_table(
            "prompt_basic",
            sa.Column(
                "id", sa.Integer(), autoincrement=True, nullable=False, comment="主键ID"
            ),
            sa.Column("space_id", sa.BigInteger(), nullable=False, comment="空间ID"),
            sa.Column(
                "prompt_key", sa.String(length=128), nullable=False, comment="Prompt key"
            ),
            sa.Column("name", sa.String(length=128), nullable=False, comment="Prompt名称"),
            sa.Column(
                "description", sa.String(length=1024), nullable=False, comment="描述"
            ),
            sa.Column(
                "created_by", sa.String(length=128), nullable=False, comment="创建人"
            ),
            sa.Column(
                "updated_by", sa.String(length=128), nullable=False, comment="更新人"
            ),
            sa.Column(
                "latest_version", sa.String(length=128), nullable=False, comment="最新版本"
            ),
            sa.Column(
                "latest_commit_time", sa.DateTime(), nullable=True, comment="最新提交时间"
            ),
            sa.Column("created_at", sa.DateTime(), nullable=False, comment="创建时间"),
            sa.Column("updated_at", sa.DateTime(), nullable=False, comment="更新时间"),
            sa.Column("deleted_at", sa.DateTime(), nullable=True),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint(
                "space_id", "prompt_key", "deleted_at", name="uq_space_prompt_deleted"
            ),
        )
    
    if not index_exists("prompt_basic", "ix_prompt_basic_space_id"):
        op.create_index(
            op.f("ix_prompt_basic_space_id"), "prompt_basic", ["space_id"], unique=False
        )

    if not table_exists("prompt_commit"):
        op.create_table(
            "prompt_commit",
            sa.Column(
                "id", sa.BigInteger(), autoincrement=True, nullable=False, comment="主键ID"
            ),
            sa.Column("space_id", sa.BigInteger(), nullable=False, comment="空间ID"),
            sa.Column("prompt_id", sa.BigInteger(), nullable=False, comment="Prompt ID"),
            sa.Column(
                "prompt_key", sa.String(length=128), nullable=False, comment="Prompt key"
            ),
            sa.Column(
                "template_type", sa.String(length=64), nullable=True, comment="模版类型"
            ),
            sa.Column("messages", sa.Text(), nullable=True, comment="托管消息列表"),
            sa.Column("prompt_model_config", sa.Text(), nullable=True, comment="模型配置"),
            sa.Column("variable_defs", sa.Text(), nullable=True, comment="变量定义"),
            sa.Column("tools", sa.Text(), nullable=True, comment="tools"),
            sa.Column("tool_call_config", sa.Text(), nullable=True, comment="tool调用配置"),
            sa.Column("version", sa.String(length=128), nullable=False, comment="版本"),
            sa.Column(
                "base_version", sa.String(length=128), nullable=False, comment="来源版本"
            ),
            sa.Column(
                "committed_by", sa.String(length=128), nullable=False, comment="提交人"
            ),
            sa.Column("description", sa.Text(), nullable=True, comment="提交版本描述"),
            sa.Column(
                "created_at",
                sa.DateTime(),
                server_default=sa.text("now()"),
                nullable=False,
                comment="创建时间",
            ),
            sa.Column(
                "updated_at",
                sa.DateTime(),
                server_default=sa.text("now()"),
                nullable=False,
                comment="更新时间",
            ),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint(
                "space_id", "prompt_id", "version", name="uq_space_prompt_commit"
            ),
        )

    if not table_exists("prompt_user_draft"):
        op.create_table(
            "prompt_user_draft",
            sa.Column(
                "id", sa.BigInteger(), autoincrement=True, nullable=False, comment="主键ID"
            ),
            sa.Column("space_id", sa.BigInteger(), nullable=False, comment="空间ID"),
            sa.Column("prompt_id", sa.BigInteger(), nullable=False, comment="Prompt ID"),
            sa.Column("user_id", sa.String(length=128), nullable=False, comment="用户ID"),
            sa.Column(
                "template_type", sa.String(length=64), nullable=True, comment="模版类型"
            ),
            sa.Column("messages", sa.Text(), nullable=True, comment="托管消息列表"),
            sa.Column("prompt_model_config", sa.Text(), nullable=True, comment="模型配置"),
            sa.Column("variable_defs", sa.Text(), nullable=True, comment="变量定义"),
            sa.Column("tools", sa.Text(), nullable=True, comment="tools"),
            sa.Column("tool_call_config", sa.Text(), nullable=True, comment="tool调用配置"),
            sa.Column(
                "base_version",
                sa.String(length=128),
                nullable=False,
                comment="草稿关联版本",
            ),
            sa.Column(
                "is_draft_edited",
                sa.Boolean(),
                nullable=False,
                comment="草稿内容是否基于BaseVersion有变更",
            ),
            sa.Column(
                "created_at",
                sa.DateTime(),
                server_default=sa.text("now()"),
                nullable=False,
                comment="创建时间",
            ),
            sa.Column(
                "updated_at",
                sa.DateTime(),
                server_default=sa.text("now()"),
                nullable=False,
                comment="更新时间",
            ),
            sa.Column("deleted_at", sa.BigInteger(), nullable=False, comment="删除时间"),
            sa.PrimaryKeyConstraint("id"),
        )

    if not table_exists("prompts"):
        op.create_table(
            "prompts",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("name", sa.String(length=255), nullable=True),
            sa.Column("content", sa.Text(), nullable=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("created_by", sa.String(length=255), nullable=True),
            sa.Column("created_at", sa.DateTime(), nullable=True),
            sa.Column("updated_at", sa.DateTime(), nullable=True),
            sa.Column("is_deleted", sa.Boolean(), nullable=True),
            sa.PrimaryKeyConstraint("id"),
        )
    
    if not index_exists("prompts", "ix_prompts_id"):
        op.create_index(op.f("ix_prompts_id"), "prompts", ["id"], unique=False)
    if not index_exists("prompts", "ix_prompts_name"):
        op.create_index(op.f("ix_prompts_name"), "prompts", ["name"], unique=True)

    if not table_exists("user"):
        op.create_table(
            "user",
            sa.Column("id", sa.BigInteger(), nullable=False, comment="Primary Key ID"),
            sa.Column(
                "name", sa.String(length=128), nullable=False, comment="User Nickname"
            ),
            sa.Column(
                "unique_name",
                sa.String(length=128),
                nullable=False,
                comment="User Unique Name",
            ),
            sa.Column("email", sa.String(length=128), nullable=False, comment="Email"),
            sa.Column("mobile", sa.Integer(), nullable=False, comment="Mobile"),
            sa.Column(
                "password",
                sa.String(length=128),
                nullable=False,
                comment="Password (Encrypted)",
            ),
            sa.Column(
                "description",
                sa.String(length=512),
                nullable=False,
                comment="User Description",
            ),
            sa.Column(
                "icon_uri", sa.String(length=512), nullable=False, comment="Avatar URI"
            ),
            sa.Column(
                "user_verified",
                sa.Boolean(),
                nullable=False,
                comment="User Verification Status",
            ),
            sa.Column(
                "country_code", sa.BigInteger(), nullable=False, comment="Country Code"
            ),
            sa.Column(
                "session_key", sa.String(length=512), nullable=False, comment="Session Key"
            ),
            sa.Column("deleted_at", sa.BigInteger(), nullable=False, comment="删除时间"),
            sa.Column("created_at", sa.DateTime(), nullable=False),
            sa.Column("updated_at", sa.DateTime(), nullable=False),
            sa.PrimaryKeyConstraint("id"),
        )

    if not table_exists("prompt_versions"):
        op.create_table(
            "prompt_versions",
            sa.Column("id", sa.Integer(), nullable=False),
            sa.Column("name", sa.String(length=255), nullable=True),
            sa.Column("prompt_id", sa.Integer(), nullable=True),
            sa.Column("version", sa.Integer(), nullable=True),
            sa.Column("content", sa.Text(), nullable=True),
            sa.Column("description", sa.Text(), nullable=True),
            sa.Column("created_by", sa.String(length=255), nullable=True),
            sa.Column("created_at", sa.DateTime(), nullable=True),
            sa.Column("is_current", sa.Boolean(), nullable=True),
            sa.ForeignKeyConstraint(
                ["prompt_id"],
                ["prompt_basic.id"],
            ),
            sa.PrimaryKeyConstraint("id"),
        )
    
    if not index_exists("prompt_versions", "ix_prompt_versions_id"):
        op.create_index(
            op.f("ix_prompt_versions_id"), "prompt_versions", ["id"], unique=False
        )
    if not index_exists("prompt_versions", "ix_prompt_versions_name"):
        op.create_index(
            op.f("ix_prompt_versions_name"), "prompt_versions", ["name"], unique=True
        )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    if index_exists("prompt_versions", "ix_prompt_versions_name"):
        op.drop_index(op.f("ix_prompt_versions_name"), table_name="prompt_versions")
    if index_exists("prompt_versions", "ix_prompt_versions_id"):
        op.drop_index(op.f("ix_prompt_versions_id"), table_name="prompt_versions")
    if table_exists("prompt_versions"):
        op.drop_table("prompt_versions")
    
    if table_exists("user"):
        op.drop_table("user")
    
    if index_exists("prompts", "ix_prompts_name"):
        op.drop_index(op.f("ix_prompts_name"), table_name="prompts")
    if index_exists("prompts", "ix_prompts_id"):
        op.drop_index(op.f("ix_prompts_id"), table_name="prompts")
    if table_exists("prompts"):
        op.drop_table("prompts")
    
    if table_exists("prompt_user_draft"):
        op.drop_table("prompt_user_draft")
    if table_exists("prompt_commit"):
        op.drop_table("prompt_commit")
    
    if index_exists("prompt_basic", "ix_prompt_basic_space_id"):
        op.drop_index(op.f("ix_prompt_basic_space_id"), table_name="prompt_basic")
    if table_exists("prompt_basic"):
        op.drop_table("prompt_basic")
    
    if table_exists("job_user_info"):
        op.drop_table("job_user_info")
    if table_exists("job_user_draft"):
        op.drop_table("job_user_draft")
    # ### end Alembic commands ###
