import os
import sys
sys.path.append(os.path.dirname(sys.path[0]))
from utils.secure_db_client import get_remote_engine


def export_data(site_name, date_type, date_info):
    engine = get_remote_engine(
        site_name="us",  # -> database "selection"
        # db_type="postgresql_cluster",  # 原导出到 pg 集群，改为 MySQL，不再维护
        db_type="mysql",  # -> 阿里云 MySQL
        # user="fangxingjun",         # -> 服务端 alias "mysql"
        # user_token="5f1b2e9c3a4d7f60"   # 可不传，走默认
    )
    partitions = {
        'site_name': site_name,
        'date_type': date_type,
        'date_info': date_info,
    }
    cols_list = ['asin', 'rating_and_comments_info', 'date_info']
    import_table = f'{site_name}_self_rating_180day_copy'
    target_table = f'{site_name}_self_rating_180day'
    # sql_drop = f"drop table if exists {import_table};"
    # sql_create = f"create table {import_table} like {target_table};"
    sql_drop = f"drop table if exists {import_table};"  # 删除依赖
    # sql_create = f"""CREATE TABLE {import_table} (LIKE {target_table} INCLUDING ALL);"""  # pg 语法，MySQL 不支持，改为下面的 like 写法
    sql_create = f"create table {import_table} like {target_table};"  # MySQL：复制目标表结构建临时表
    engine.execute(sql_drop)
    engine.execute(sql_create)
    print(f"sql_drop: {sql_drop}")
    print(f"sql_create: {sql_create}")
    engine.sqoop_raw_export(
        hive_table='dwt_self_asin_detail_rating',
        import_table=import_table,
        partitions=partitions,
        m=1,
        cols=','.join(cols_list)
    )
    engine.swap_tables(
        source_table=import_table,
        target_table=target_table
    )


if __name__ == '__main__':
    # site_name = 'us'
    # date_type = 'month'
    # date_info = '2026-01'
    site_name = sys.argv[1]  # 参数1：站点
    date_type = sys.argv[2]  # 参数2：类型：week/4_week/month/quarter/day
    date_info = sys.argv[3]  # 参数3：年-周/年-月/年-季/年-月-日, 比如: 2022-1
    export_data(site_name, date_type, date_info)
