"""
   @Author      : hejiangming
   @Description : 周趋势图独立导出：Hive dwt_st_base_report(week) → PG集群 {site}_aba_last_total_week(自动建年分区)
   @SourceTable : dwt_st_base_report (date_type=week)
   @SinkTable   : {site}_aba_last_total_week (PG集群, 按年 RANGE 分区)
   @CreateTime  : 2026/07/17 12:05
   @UpdateTime  : 2026/07/17 12:05
"""
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
from utils.hdfs_utils import HdfsUtils

if __name__ == '__main__':
    site_name = CommonUtil.get_sys_arg(1, None)   # 参数1：站点 us/uk/de
    date_type = CommonUtil.get_sys_arg(2, None)   # 参数2：固定 week
    date_info = CommonUtil.get_sys_arg(3, None)   # 参数3：周 2025-24
    print(f"执行参数为{sys.argv}")


    CommonUtil.judge_is_work_hours(
        site_name=site_name, date_type=date_type, date_info=date_info,
        principal='hejiangming', priority=1, export_tools_type=1, belonging_to_process='ABA周增长趋势图'
    )

    # ============================================================
    # 趋势导 PG 集群(postgresql_cluster)。逻辑照搬 sqoop_export/dim_st_detail_week.py
    #   (us 现有趋势导出)，抽出来三站共用。
    # ============================================================
    db_type = DbTypes.postgresql_cluster.name
    year_str = CommonUtil.safeIndex(date_info.split("-"), 0, None)
    year_next = str(int(year_str) + 1)

    master_tb = f"{site_name}_aba_last_total_week"
    export_tb = f"{master_tb}_{year_str}"

    engine = DBUtil.get_db_engine(db_type, site_name)

    hive_path = CommonUtil.build_hdfs_path(
        "dwt_st_base_report",
        partition_dict={"site_name": site_name, "date_type": date_type, "date_info": date_info},
    )
    if not HdfsUtils.read_list(hive_path):
        print(f"[ERROR] Hive 分区无数据文件：{hive_path}，跳过导出(不删PG)，请先检查趋势计算任务！")
        engine.dispose()
        sys.exit(1)
    print(f"Hive 分区有数据：{hive_path}，继续导出")

    # ============================================================
    # 建当年分区子表 + st_key 索引 + 清本周
    # 【为什么 create if not exists partition of】趋势表是「顶层母表 + 按年 RANGE 分区子表」，
    #   新一年第一次导出自动建该年子表，不用手动预建
    # 【为什么先 delete 本周】导出是「先删该周、再 sqoop append」，幂等；Hive 有数据重跑即补回
    # ============================================================
    sql = f"""
        create table if not exists {export_tb} partition of {master_tb} for values from ('{year_str}') to ('{year_next}');
        create index if not exists {export_tb}_st_key_idx on {export_tb} using btree (st_key);
        delete from {export_tb} where date_info = '{date_info}';
    """
    print("================================执行sql================================")
    print(sql)
    DBUtil.engine_exec_sql(engine, sql)

    # sqoop 导出：Hive dwt_st_base_report 对应分区 → PG 子表
    columns = ["st_key", "search_term", "st_volume", "st_rank", "st_orders", "years",
               "created_time", "updated_time", "date_type", "date_info"]
    sh = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_st_base_report",
        export_tb=export_tb,
        col=columns,
        partition_dict={
            "site_name": site_name,
            "date_type": "week",
            "date_info": date_info
        }
    )
    client = SSHUtil.get_ssh_client()
    SSHUtil.exec_command_async(client, sh, ignore_err=False)
    client.close()
    print("================================周趋势图导出完成================================")

