import time
import json
from datetime import datetime

import pymysql
from loguru import logger

from inv_img_double_search import AmazonImageSearch
DB_CONFIG = {
    'host': 'rm-wz9yg9bsb2zf01ea4yo.mysql.rds.aliyuncs.com',       # 你的数据库IP (如果是远程数据库请填写公网IP)
    'port': 3306,
    'user': 'adv_test',            # 数据库用户名
    'password': 'jBVQe0FAwZgY3YsQqfwzUd', # 数据库密码
    'db': 'selection',      # 数据库名
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}
def get_db_conn():
    return pymysql.connect(**DB_CONFIG)
def worker_loop():
    logger.info("VPS Worker 已启动，监听任务中...")
    while True:
        conn = None
        try:
            conn = get_db_conn()
            with conn.cursor() as cursor:
                # 1. 抢任务  优先处理早期任务
                sql_get = "SELECT id, img_url FROM us_inv_img_result WHERE state = 1 ORDER BY id ASC LIMIT 1"
                cursor.execute(sql_get)
                task = cursor.fetchone()

                if task:
                    task_id = task['id']
                    url = task['img_url']
                    logger.info(f"领取任务: {task_id}")

                    # ===================================================
                    # 阶段 A: 标记为进行中 (手动更新 updated_at)
                    # ===================================================
                    now_time = datetime.now()  # 获取 VPS 当前时间

                    # 更新 updated_at
                    cursor.execute(
                        "UPDATE us_inv_img_result SET state = 2, updated_at = %s WHERE id = %s",
                        (now_time, task_id)
                    )
                    conn.commit()

                    try:
                        # 执行爬虫
                        spider = AmazonImageSearch(site_name="us")
                        result_data = spider.search(url)
                        json_result = json.dumps(result_data, ensure_ascii=False)

                        # ===================================================
                        # 阶段 B: 标记为完成 (手动更新 updated_at)
                        # ===================================================
                        finish_time = datetime.now()  # 获取完成时间

                        cursor.execute(
                            "UPDATE us_inv_img_result SET state = 3, result_data = %s, updated_at = %s WHERE id = %s",
                            (json_result, finish_time, task_id)
                        )
                        conn.commit()
                        logger.success(f"任务 {task_id} 完成")

                    except Exception as e:
                        logger.error(f"任务 {task_id} 报错: {e}")
                        # error_json = json.dumps({"success": 0, "msg": str(e)}, ensure_ascii=False)

                        # ===================================================
                        # 阶段 C: 标记为报错 (手动更新 updated_at)
                        # ===================================================
                        # fail_time = datetime.now()

                        # cursor.execute(
                        #     "UPDATE us_inv_img_result SET state = 3, result_data = %s, updated_at = %s WHERE id = %s",
                        #     (error_json, fail_time, task_id)
                        # )
                        # conn.commit()
                else:
                    time.sleep(0.5)

        except Exception as e:
            logger.error(f"数据库连接失败: {e}")
            time.sleep(3)
        finally:
            if conn: conn.close()


if __name__ == "__main__":
    worker_loop()