import os
import sys

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


def export():
    site_name = CommonUtil.get_sys_arg(1, 'us')
    batch = CommonUtil.get_sys_arg(2, '2024-06-23')

    db_type = DbTypes.postgresql_cluster.name
    export_tb = f"us_merchantwords_top_asin_2024"
    hive_tb = "dwt_merchantwords_top_asin_info"
    export_tb_copy = f"{export_tb}_copy"
    # assert CommonUtil.judge_not_working_hour(), "工作时间，请谨慎导出！！！！"
    # engine = DBUtil.get_db_engine(db_type, site_name)
    sql = f"""
        drop table if exists {export_tb_copy};
        create table if not exists {export_tb_copy}   ( like {export_tb}  including comments );
    """
    DBUtil.exec_sql(db_type, site_name, sql, dispose_flag=True)
    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb=hive_tb,
        export_tb=export_tb_copy,
        col=[
            "keyword",
            "zr_top_asin_list",
            "zr_rank_list",
        ],
        partition_dict={
            "site_name": site_name,
            "batch": batch,
        }
    )
    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()

    DBUtil.exchange_tb(
        DBUtil.get_db_engine(db_type, site_name),
        source_tb_name=export_tb_copy,
        target_tb_name=export_tb,
        cp_index_flag=True,
    )
    pass


if __name__ == '__main__':
    export()
