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, DbTypes

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)
    date_info = CommonUtil.get_sys_arg(2, None)
    tb_type = CommonUtil.get_sys_arg(3, None)
    #  获取最后一个参数
    test_flag = CommonUtil.get_sys_arg(len(sys.argv) - 1, None)
    print(f"执行参数为{sys.argv}")
    CommonUtil.judge_is_work_hours(
        site_name=site_name,
        date_type="day",
        date_info=date_info,
        principal='hejiangming',
        priority=1,
        export_tools_type=1
    )

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

    db_type = DbTypes.postgresql_cluster.name

    suffix = CommonUtil.reformat_date(date_info, "%Y-%m-%d", "%Y_%m_%d", )
    export_master_tb = f"{site_name}_{tb_type}_asin_rank"
    export_tb = f"{export_master_tb}_{suffix}"
    next_day = CommonUtil.get_day_offset(date_info, 1)

    engine = DBUtil.get_db_engine(db_type, site_name)
    #  根据主表 复制结构 创建天的子表 day_flag 是一个自动计算列，由 is_1_day_flag + is_7_day_flag + is_30_day_flag
    DBUtil.engine_exec_sql(engine, f"""
           drop table if exists {export_tb};
           create table {export_tb} ( like {export_master_tb} including defaults including constraints );
           alter table {export_tb}	drop  if exists day_flag ;
           alter table {export_tb} add column day_flag   varchar(10)  generated always as (is_1_day_flag + is_7_day_flag + is_30_day_flag) stored;
                """)
    engine.dispose()

    # 导出表名 Sqoop 导出 Hive → PG
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb=f"dwd_{tb_type}_asin_rank",
        export_tb=export_tb,
        col=[
            "asin",
            "category_id",
            "bsr_rank",
            "is_1_day_flag",
            "is_7_day_flag",
            "is_30_day_flag",
            "bsr_count",
            "is_asin_new",
            "is_asin_bsr_new",
            "last_bsr_day",
            "date_info",
        ],
        partition_dict={
            "site_name": site_name,
            "date_type": "last30day",
            "date_info": date_info
        }
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    # 把今天的子表挂到主表上，查询主表时自动路由到对应日期的子表。
    sql = f"""alter table {export_master_tb} attach partition {export_tb} for values from ('{date_info}') to ('{next_day}' );"""
    # 变成分布式表
    DBUtil.exec_sql(db_type=db_type, site_name=site_name, sql=sql, dispose_flag=True)

    # 插入当前的记录数据到MySQL  记录导出状态
    update_sql = f"""
     insert ignore into workflow_everyday (site_name, report_date, status, status_val, table_name, date_type, page, is_end, remark, export_db_type,freeze_flag)
                   values ('{site_name}', '{date_info}', '导出PG数据库', 14, '{site_name}_{tb_type}_asin_rank', 'day', '{str(tb_type).upper()}榜单', '是', '{str(tb_type).upper()}榜单对应的TOP100ASIN','{db_type}','enable')
    """

    DBUtil.exec_sql(DbTypes.mysql.name, "us", update_sql, dispose_flag=True)

    update_sql = f"""
      update workflow_everyday   set export_db_type ='postgresql_cluster', freeze_flag='enable'
            where table_name = '{site_name}_{tb_type}_asin_rank' and report_date in ('{date_info}');
"""
    DBUtil.exec_sql(DbTypes.mysql.name, "us", update_sql, dispose_flag=True)
    print("success")
