import os
import sys
import time

import pandas as pd

os.environ["PYARROW_IGNORE_TIMEZONE"] = "1"
sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from utils.templates import Templates
from utils.db_util import DbTypes, DBUtil
from datetime import date


class ImgAlterTableName(Templates):

    def __init__(self, site_name='us', img_type="amazon_inv"):
        super(ImgAlterTableName, self).__init__()
        self.site_name = site_name
        self.img_type = img_type
        self.engine_doris = DBUtil.get_db_engine(db_type=DbTypes.doris.name, site_name=self.site_name)
        self.spark = self.create_spark_object(app_name=f"{self.db_save}: {self.site_name}")

    def read_data(self):
        pass

    def handle_data(self):
        while True:
            with self.engine_doris.begin() as conn:
                sql1 = "ALTER TABLE img_id_index RENAME img_id_index_temp;"
                conn.execute(sql1)
                sql2 = "ALTER TABLE img_id_index_copy RENAME img_id_index;"
                conn.execute(sql2)
                sql3 = "ALTER TABLE img_id_index_temp RENAME img_id_index_copy;"
                conn.execute(sql3)
            print(f"交换表名称完成--sql1: {sql1}\nsql2: {sql2}\nsql3: {sql3}")
            sql_read = "select * from img_id_index limit 1"
            df_read = pd.read_sql(sql_read, con=self.engine_doris)
            created_time = str(list(df_read.created_time)[0])
            created_date = created_time[:10] if len(created_time) > 10 else None
            # 获取今天日期
            today_str = date.today().strftime('%Y-%m-%d')  # '2025-08-20'
            if created_date == today_str:
                print(f"日期校验通过: created_date--{created_date}, today_str--{today_str}")
                break
            else:
                print(f"日期校验不通过，等待10s继续: created_date--{created_date}, today_str--{today_str}")
                self.engine_doris = DBUtil.get_db_engine(db_type=DbTypes.doris.name, site_name=self.site_name)
                time.sleep(10)
                continue

    def save_data(self):
        pass


if __name__ == '__main__':
    site_name = sys.argv[1]
    img_type = sys.argv[2]
    handle_obj = ImgAlterTableName(site_name=site_name, img_type=img_type)
    handle_obj.run()