import os
import sys

sys.path.append(os.path.dirname(sys.path[0]))

from utils.db_util import DBUtil
from utils.ssh_util import SSHUtil
from utils.common_util import CommonUtil

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)
    date_type = CommonUtil.get_sys_arg(2, None)
    date_info = CommonUtil.get_sys_arg(3, None)

    #  获取最后一个参数
    test_flag = CommonUtil.get_sys_arg(len(sys.argv) - 1, None)
    print(f"执行参数为{sys.argv}")

    if test_flag == 'test':
        db_type = 'postgresql_test'
        print("导出到测试库中")
    else:
        db_type = "postgresql_cluster"
        print("导出到PG集群库库中")

    year_str = CommonUtil.safeIndex(date_info.split("-"), 0, None)
    suffix = str(date_info).replace("-", "_")
    base_tb = f"{site_name}_aba_st_theme_agg"
    export_master_tb = f"{base_tb}_{year_str}"
    export_tb = f"{base_tb}_{suffix}"
    next_month = CommonUtil.get_next_val(date_type, date_info)

    # 获取数据库连接
    engine = DBUtil.get_db_engine(db_type, site_name)

    # 保证幂等性，先删除原始表同周期的数据
    sql = f"""
        drop table if exists {export_tb};
        create table if not exists {export_tb} (
            like {export_master_tb}  including ALL 
        );
    """
    DBUtil.engine_exec_sql(engine, sql)

    # 导出agg表
    sh_report = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_st_theme_agg",
        export_tb=export_tb,
        col=[
            "pattern_st",
            "pattern_bsr_orders_total",
            "pattern_st_count",
            "theme_ch",
            "theme_en",
            "theme_label_ch",
            "theme_label_en",
            "theme_label_bsr_orders",
            "theme_label_counts",
            "pattern_bsr_orders_rate",
            "pattern_num_rate",
            "date_info",
            "created_time",
            "updated_time",
            "pattern_word_num",
            "pattern_category_id",
            "pattern_category_current_id",
            "pattern_rank",
            "pattern_rank_change_rate",
            "pattern_rank_rate_of_change"
        ],
        partition_dict={
            "site_name": site_name,
            "date_type": date_type,
            "date_info": date_info
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh_report, ignore_err=False)

    client.close()
    # 创建索引并交换分区
    DBUtil.add_pg_part(
        engine,
        source_tb_name=export_tb,
        part_master_tb=export_master_tb,
        part_val={
            "from": [date_info],
            "to": [next_month]
        },
        cp_index_flag=False,
    )

    update_workflow_sql = f"""
    REPLACE INTO selection.workflow_everyday (site_name, report_date, status, status_val, table_name, date_type, page, is_end, remark, created_at, export_db_type) 
    VALUES('{site_name}', '{date_info}', '导出PG数据库完成', 14, '{base_tb}', '{date_type}', 'ABA主题标签', '是', 'ABA主题标签', CURRENT_TIME, 'postgresql_cluster');
            """
    mysql_engine = DBUtil.get_db_engine('mysql', 'us')
    DBUtil.engine_exec_sql(mysql_engine, update_workflow_sql)

    # 关闭链接
    engine.dispose()
    mysql_engine.dispose()

    print("success")
