import pandas as pd
from sqlalchemy import create_engine


def get_country_engine(site_name="us"):
    # 119.23.61.82
    # root
    # 8TspXes2ZznEooth
    Mysql_arguments = {
        'user': 'XP_Yswg2025',
        'password': 'Xp_Yswg2025%40300',
        'host': 'rm-wz9yg9bsb2zf01ea4yo.mysql.rds.aliyuncs.com',
        'port': 3306,
        'database': 'selection',
        'charset': 'utf8',
    }
    if site_name == 'us' or site_name == 'mx' or site_name == "ca":
        Mysql_arguments["database"] = f"selection"
        db_ = 'mysql+pymysql://{}:{}@{}:{}/{}?charset={}'.format(*Mysql_arguments.values())
    elif site_name == "keepa":
        db_ = 'mysql+pymysql://{}:{}@{}:{}/{}?charset={}'.format(*keepa_mysql.values())
    else:
        Mysql_arguments["database"] = f"selection_{site_name}"
        db_ = 'mysql+pymysql://{}:{}@{}:{}/{}?charset={}'.format(*Mysql_arguments.values())
    engine = create_engine(db_)  # , pool_recycle=3600
    return engine


def get_pg_country_engine(site_name="us"):
    h6_pg_us = {
        'user': 'postgres',
        'password': 'fazAqRRVV9vDmwDNRNb593ht5TxYVrfTyHJSJ3BS',
        'host': '192.168.10.224',
        'port': 5433,
        'database': 'selection',
        # 'encoding': 'utf-8',
    }
    if site_name not in ['uk', 'fr', 'es', 'it', 'de']:
        h6_pg_us["database"] = f"selection"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h6_pg_us.values())
    else:
        h6_pg_us["database"] = f"selection_{site_name}"
        db_ = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(*h6_pg_us.values())
    # engine = create_engine(db_, poolclass=NullPool, connect_args={'connect_timeout': 10})  # , pool_recycle=3600
    engine = create_engine(db_, pool_timeout=300, connect_args={'connect_timeout': 10})  # , pool_recycle=3600
    return engine

del_sql = "delete FROM us_self_asin_detail WHERE updated_at < DATE_SUB(NOW(), INTERVAL 15 DAY);"

# 查询语句（参数化防止注入）
sql_read = "SELECT * FROM us_self_asin_detail WHERE updated_at >= DATE_SUB(NOW(), INTERVAL 1 DAY);"

# 查询并读取数据
with get_country_engine('us').connect() as conn:
    del_result = conn.execute(del_sql)
    print('数据清理成功')
    result = conn.execute(sql_read)
    # result = conn.execute(sql_read, {'asin': 'B0FC6FK4RB'})

    # 获取列名和数据
    columns = [desc[0] for desc in result.cursor.description]
    data = result.fetchall()

print('开始备份')
# 转为 DataFrame
df = pd.DataFrame(data=data, columns=columns)
del df['id']

df.loc[df['launch_time'] == '0000-00-00', 'launch_time'] = None

df.to_sql('us_self_asin_detail_2025', con=get_pg_country_engine('us'), if_exists="append", index=False, method='multi', chunksize=10000)

# 20 23 * * * cd /mnt/\*/hezhe/utils && /opt/module/anaconda3/envs/pyspark/bin/python backup_self_asin_detail.py > backup.log 2>&1 &


