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)
    if not ((site_name in ['us', 'uk', 'de']) and (date_type == 'month') and (date_info >= '2024-04')):
        print("暂不计算该维度数据！")
        quit()

    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       
            );
            
            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;
            $$;
        """
        print("================================执行sql================================")
        print(sql)
        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",
            "weekly_sales",
            "weekly_views",
            "monthly_sales",
            "monthly_views",
            "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

