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 DBUtil

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)

    db_type = "postgresql_cluster"
    print("导出到PG集群中")

    export_master_tb = f"{site_name}_asin_bs_category_desc"
    export_tb = f"{export_master_tb}_tmp"

    engine = DBUtil.get_db_engine(db_type, site_name)
    with engine.connect() as connection:
        sql = f"""
        drop table if exists {export_master_tb}_old;
        CREATE TABLE {export_tb} (LIKE {export_master_tb} INCLUDING ALL);
                """
        print("================================执行sql================================")
        print(sql)
        connection.execute(sql)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dim_asin_bs_category_desc",
        export_tb=export_tb,
        col=[
            "asin",
            "best_sellers_rank",
            "last_herf",
            "date_info",
            "bs_rank_str",
            "bs_category_str"
        ],
        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)
    with engine.connect() as connection:
        sql = f"""
        ALTER TABLE {export_master_tb} RENAME TO {export_master_tb}_old;
        ALTER TABLE {export_tb} RENAME TO {export_master_tb};
        """
        print("================================执行sql================================")
        print(sql)
        connection.execute(sql)

    print("success")
