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)
    CommonUtil.judge_is_work_hours(site_name=site_name, date_type=date_type, date_info=date_info,
                                   principal='chenyuanjie', priority=1, export_tools_type=1)

    db_type = "postgresql_cluster"
    print("导出到PG集群")
    master_tb = f"{site_name}_amazon_report"
    export_tb = f"{site_name}_amazon_report_copy"

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

    with engine.connect() as connection:
        sql = f"""
            drop table if exists {export_tb};
            create table if not exists {export_tb} 
            (
            like {master_tb} including ALL       
            );

            SELECT create_distributed_table('{export_tb}', 'asin');

            DO $$
            DECLARE
                index_record RECORD;
            BEGIN
                FOR index_record IN (SELECT indexname FROM pg_indexes WHERE tablename = '{export_tb}') 
                LOOP
                    EXECUTE 'DROP INDEX IF EXISTS ' || index_record.indexname;
                END LOOP;
            END;
            $$;
        """
        connection.execute(sql)

    # 导出脚本
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_amazon_report",
        export_tb=export_tb,
        col=[
            "asin",
            "monthly_sales",
            "zr_count",
            "sp_count",
            "total_count",
            "date_info_list"
        ],
        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, ignore_err=False)
    client.close()

    print("导出完成，准备创建索引和交换表名")
    DBUtil.exchange_tb(engine, export_tb, master_tb, True)

    engine.dispose()
    print("success")

pass
