import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))
from utils.db_util import DBUtil, DbTypes
from utils.ssh_util import SSHUtil
from utils.common_util import CommonUtil

"""
标题历史数据导出
"""


def export():
    site_name = CommonUtil.get_sys_arg(1, None)
    #  获取最后一个参数
    test_flag = CommonUtil.get_sys_arg(len(sys.argv) - 1, None)

    if test_flag == 'test':
        db_type = DbTypes.postgresql_test.name
    else:
        assert CommonUtil.judge_not_working_hour(), "工作时间，请谨慎导出！！！！"
        db_type = DbTypes.postgresql_cluster.name
    print(f"导出到{db_type}中")

    # 先导出到copy表
    export_tb = f"{site_name}_asin_title_history"
    export_tb_copy = f"{export_tb}_copy"

    DBUtil.exec_sql(
        db_type=db_type,
        site_name=site_name,
        sql=f"""
        drop table if exists {export_tb_copy};
        create table if not exists {export_tb_copy}
        (
            like {export_tb} including indexes including comments
        );
    """,
        dispose_flag=True)

    # 导出到集群的话对copy表使用分布式数据
    if db_type == DbTypes.postgresql_cluster.name:
        # 创建分布式表
        DBUtil.exec_sql(db_type, site_name, f"""
            select create_distributed_table('{export_tb_copy}', 'asin');
    """, True)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_asin_title_history",
        export_tb=export_tb_copy,
        col=[
            "asin",
            "title_time_list",
            "title_list",
        ],
        partition_dict={
            "site_name": site_name
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    engine = DBUtil.get_db_engine(db_type, site_name)
    # # 交换表名
    DBUtil.exchange_tb(engine,
                       source_tb_name=export_tb_copy,
                       target_tb_name=export_tb,
                       cp_index_flag=False)
    # 删除copy表
    DBUtil.engine_exec_sql(engine, f"""
            drop table if exists {export_tb_copy};
    """)
    engine.dispose()
    pass


if __name__ == '__main__':
    export()
