import os
import sys
from datetime import datetime

sys.path.append(os.path.dirname(sys.path[0]))
from utils.ssh_util import SSHUtil
from utils.common_util import CommonUtil, DateTypes
from utils.db_util import DBUtil
from utils.hdfs_utils import HdfsUtils

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("导出到PG测试库中")
    else:
        CommonUtil.judge_is_work_hours(site_name=site_name, date_type=date_type, date_info=date_info,
                                       principal='chenyuanjie', priority=2, export_tools_type=1,  belonging_to_process=f'新ABA流程_{date_type}')
        if date_type in (DateTypes.month.name, DateTypes.week.name, DateTypes.month_week.name):
            db_type = 'postgresql_cluster'
            print("导出到PG-Cluster库中")
        else:
            db_type = "postgresql"
            print("导出到PG库中")

    # 获取数据库连接
    engine = DBUtil.get_db_engine(db_type, site_name)
    # 导出前校验 Hive 分区是否有数据，避免空分区触发交换导致 PG 数据被清空
    hive_partition_path = f"/home/big_data_selection/dwt/dwt_aba_last_change_rate/site_name={site_name}/date_type={date_type}/date_info={date_info}"
    hive_files = HdfsUtils.read_list(hive_partition_path)
    if not hive_files:
        print(f"[ERROR] Hive 分区无数据文件，路径：{hive_partition_path}，跳过导出，请先检查 DWT 计算任务是否正常写入！")
        engine.dispose()
        sys.exit(1)
    print(f"Hive 分区文件数：{len(hive_files)}，路径：{hive_partition_path}，继续导出")
    # 导出表
    export_base_tb = f"{site_name}_aba_last_change_rate"

    # last30day和last365day导出
    if date_type in (DateTypes.last30day.name, DateTypes.last365day.name,DateTypes.month_week.name):
        if date_type == DateTypes.month_week.name:
            export_tb_target = f"{export_base_tb}_last30day"
        else:
            export_tb_target = f"{export_base_tb}_{date_type}"  # us_aba_last_change_rate_last30day / _last365day
        export_tb_copy = f"{export_tb_target}_copy"
        export_tb = export_tb_copy
        # 如果copy表不存在则创建copy表
        sql = f"""
               create table if not exists {export_tb_copy} 
              (
                  like {export_tb_target} including indexes including comments
              );
              truncate table {export_tb_copy};
              """
        DBUtil.engine_exec_sql(engine, sql)
    else:
        # day,week,month这种时间类型的数据导出
        date_partition = str(date_info).replace("-", "_")
        export_tb = f"{site_name}_aba_last_change_rate_{date_type}_{date_partition}"
        next_val = CommonUtil.get_next_val(date_type, date_info)
        # 创建分区，并清空导出分区
        sql = f"""
              create table if not exists {export_tb} partition of {export_base_tb} for values from ('{date_type}', '{date_info}') to ('{date_type}', '{next_val}');
              truncate table {export_tb};
              """
        DBUtil.engine_exec_sql(engine, sql)

    if test_flag == "month_append":
        partition_dict = {
            "site_name": site_name,
            "date_type": "month",
            "date_info": date_info
        }
    else:
        partition_dict = {
            "site_name": site_name,
            "date_type": date_type,
            "date_info": date_info
        }
    # 基础导出字段（所有 date_type 通用）
    export_base_cols = [
        "search_term",
        "search_term_id",
        "date_type",
        "date_info",
        "rank_change_rate",
        "bsr_orders_change_rate",
        "cn_seller_change_rate",
        "fbm_change_rate",
        "amazon_change_rate",
        "rank_rate_of_change",
        "bsr_orders_rate_of_change",
        "cn_seller_rate_of_change",
        "fbm_rate_of_change",
        "amazon_rate_of_change",
        "created_time",
        "updated_time"
    ]

    # 需求1：12 个新字段为 month 月度专属
    # - dwt_aba_last_change_rate_new.py 中 handle_rank_rate_history 仅 month 类型才计算实际值
    # - 其他 date_type（day/week/last30day/last365day）走 handle_rank_rate_padding 填 null
    # - 既然非 month 全是 null，就不该导出（避免污染 PG，避免 last365day 等独立表强制加列）
    if date_type == DateTypes.month.name:
        month_extra_cols = [
            "rank_rate_last_1_month",
            "rank_rate_1_month_ago",
            "rank_rate_2_month_ago",
            "rank_rate_3_month_ago",
            "rank_rate_4_month_ago",
            "rank_rate_5_month_ago",
            "rank_change_last_1_month",
            "rank_change_1_month_ago",
            "rank_change_2_month_ago",
            "rank_change_3_month_ago",
            "rank_change_4_month_ago",
            "rank_change_5_month_ago"
        ]
        export_cols = export_base_cols + month_extra_cols
    else:
        export_cols = export_base_cols


    # 导出表名
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_aba_last_change_rate",
        export_tb=export_tb,
        col=export_cols,
        partition_dict=partition_dict
    )

    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    # 关闭链接
    engine.dispose()


    if date_type in (DateTypes.last30day.name, DateTypes.last365day.name,DateTypes.month_week.name):
        #  需要通过备份表替换形式替换数据
        DBUtil.exchange_tb(engine, export_tb_copy, export_tb_target, 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,export_db_type)
            VALUES('{site_name}', '{datetime.now().date()}', '导出PG数据库完成', 14, 'us_aba_last_30_day', '30_day', 'ABA搜索词', '是', 'ABA搜索词最近30天表','{db_type}');
        """
    else:
        update_workflow_sql = f"""
            UPDATE selection.workflow_everyday SET status='导出PG数据库完成', status_val=14,is_end ='是',export_db_type = '{db_type}'  
            WHERE site_name= '{site_name}' and date_type='{date_type}' and report_date= '{date_info}'  and page ='ABA搜索词'
        """
    # 往导出流程表插入导出完成数据，方便监听导出脚本是否全部完成
    CommonUtil.modify_export_workflow_status(update_workflow_sql, site_name, date_type, date_info)
