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

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, 'us')
    batch = CommonUtil.get_sys_arg(2, '2024-1')

    db_type = DbTypes.postgresql_cluster.name
    export_tb = f"merchantwords_st_detail_2024"
    hive_tb = "dwt_merchantwords_st_detail"

    assert CommonUtil.judge_not_working_hour(), "工作时间，请谨慎导出！！！！"

    engine = DBUtil.get_db_engine(db_type, site_name)

    # 导出数据前先清空表数据
    sql = f"""truncate table {export_tb};"""
    DBUtil.engine_exec_sql(engine, sql)

    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb=hive_tb,
        export_tb=export_tb,
        col=[
            "keyword",
            "volume",
            "avg_3m",
            "avg_12m",
            "depth",
            "results_count",
            "sponsored_ads_count",
            "page_1_reviews",
            "appearance",
            "last_seen",
            "update_time",
            "source_type",
            "api_json",
            "lang",
            "site_name"
        ],
        partition_dict={
            "site_name": site_name,
            "batch": batch,
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    # 导入成功后gin索引重新建立
    sql = "reindex index  merchantwords_st_detail_keyword_tsv_idx;"
    DBUtil.engine_exec_sql(engine, sql)
    engine.dispose()
