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
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}")

    CommonUtil.judge_is_work_hours(site_name=site_name, date_type=date_type, date_info=date_info,
                                   principal='hejiangming',
                                   priority=2, export_tools_type=1, belonging_to_process='店铺流程')

    if test_flag == 'test':
        db_type = 'postgresql_test'
        print("导出到测试库中")
    else:
        db_type = "postgresql_cluster"
        print("导出到PG集群库库中")

    year_str = CommonUtil.safeIndex(date_info.split("-"), 0, None)
    suffix = str(date_info).replace("-", "_")
    base_tb = f"{site_name}_fb_base_report"
    export_master_tb = f"{base_tb}_{year_str}"
    # 上一年母表，跨年时用它 like 出当年母表（见下面建表 sql）
    export_master_tb_before = f"{base_tb}_{int(year_str) - 1}"
    export_tb = f"{base_tb}_{suffix}"
    next_month = CommonUtil.get_next_val(date_type, date_info)

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

    # 导出前校验 Hive 分区是否有数据，避免空分区触发交换导致 PG 数据被清空
    hive_partition_path = f"/home/big_data_selection/dwt/dwt_fb_base_report/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}，继续导出")

    # 跨年自动建当年母表：用上一年母表 like 出来（including all 带上索引/约束/默认值/注释），按 date_info 分区
    # 不建的话跨年第一个月（如 2027-01）下面 like {export_master_tb} 会报表不存在
    # if not exists 幂等，已存在直接跳过、只加不删
    # 保证幂等性，先删除原始表同周期的数据
    sql = f"""
         create table if not exists {export_master_tb}
                (like {export_master_tb_before} including all)
         partition by range (date_info);
         drop table if exists {export_tb};
         create table if not exists {export_tb}
                (
                like {export_master_tb}  including comments
         );
    """
    DBUtil.engine_exec_sql(engine, sql)

    # 导出agg表
    sh_report = CommonUtil.build_export_sh(
        site_name=site_name,
        db_type=db_type,
        hive_tb="dwt_fb_base_report",
        export_tb=export_tb,
        col=[
            "seller_id",
            "account_name",
            "fb_country_name",
            "fb_web_asin_num",
            "is_self_fb",
            "top_20_avg_price",
            "top_20_avg_rating",
            "top_20_avg_total_comments",
            "count_30_day_num",
            "count_1_year_num",
            "count_lifetime_num",
            "count_30_day_rate",
            "count_1_year_rate",
            "count_life_time_rate",
            "fb_new_asin_num",
            "fb_asin_total",
            "fb_new_asin_rate",
            "fb_variant_rate",
            "fb_more_variant_num",
            "fb_variant_asin_total",
            "fb_pq_rate",
            "fb_pq_num",
            "fb_crawl_date",
            "created_time",
            "updated_time",
            "date_info",
            "top_20_new_asin_num",
            "fb_country_name_type",
            "fb_account_type",
            "fb_asin_total_type",
            "fb_new_asin_num_type",
            "fb_new_asin_rate_type",
            "usr_mask_type",
            "usr_mask_progress",
            "business_name",
            "business_addr",
            "rating_30_day_num",
            "rating_90_day_num",
            "rating_1_year_num",
            "rating_lifetime_num",
            # 功能1：销量展示
            "fb_shop_total_sales",
            "fb_shop_home_sales",
            "fb_shop_home_null_flag",
            # 功能2：FBM 占比
            "fb_fbm_asin_num",
            "fb_fbm_valid_asin_num",
            "fb_fbm_rate",
            "fb_fbm_valid_rate",
            # 功能3：Hot New 榜单
            "fb_nsr_asin_num",
            "fb_nsr_rate",
            # 功能4：Best Seller 榜单
            "fb_bs_asin_num",
            "fb_bs_rate",
            # 功能5：新品销量占比 / 新品数量占比（流量选品口径）
            "fb_new_asin_sales_rate",
            # 功能6：新品/老品平均利润率
            "fb_new_ocean_profit_rate",
            "fb_new_air_profit_rate",
            "fb_old_ocean_profit_rate",
            "fb_old_air_profit_rate",
            "fb_flow_new_asin_rate",
            # 功能7：店铺综合评分（各星级占比）
            "fb_star_5_pct",
            "fb_star_4_pct",
            "fb_star_3_pct",
            "fb_star_2_pct",
            "fb_star_1_pct",
            # Feedback 同比变化率（对比去年同月）
            "count_30_day_yoy_rate",
            "count_1_year_yoy_rate",
            "count_life_time_yoy_rate"
        ],
        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_report, ignore_err=False)

    client.close()
    # 创建索引并交换分区
    DBUtil.add_pg_part(
        engine,
        source_tb_name=export_tb,
        part_master_tb=export_master_tb,
        part_val={
            "from": [date_info],
            "to": [next_month]
        },
        cp_index_flag=False,
    )

    update_workflow_sql = f"""
        update selection.workflow_progress set `status`='导出pg集群完成', status_val=6, over_date=CURRENT_TIME, is_end='是' where page='店铺Feedback'
        and `date_info`='{date_info}' and date_type='{date_type}' and site_name='{site_name}'
    """
    CommonUtil.modify_export_workflow_status(update_workflow_sql, site_name, date_type, date_info)

    # 关闭链接
    engine.dispose()
    print("success")
