import argparse
import logging.config
import traceback
from time import sleep

from sqlalchemy import update

from auto_email.error_email import send_error_email
from db import MysqlSession
from db.mysql import ZxPhhd
from log import LOGGING_CONFIG
from photo_mask import photo_mask, SEND_ERROR_EMAIL

if __name__ == '__main__':
    program_name = "照片审核自动涂抹脚本"
    logging.config.dictConfig(LOGGING_CONFIG)

    parser = argparse.ArgumentParser()
    parser.add_argument("--clean", default=False, type=bool, help="是否将涂抹中的案子改为待涂抹状态")
    args = parser.parse_args()
    if args.clean:
        # 主要用于启动时，清除仍在涂抹中的案子
        session = MysqlSession()
        update_flag = (update(ZxPhhd).where(ZxPhhd.paint_flag == "2").values(paint_flag="1"))
        session.execute(update_flag)
        session.commit()
        session.close()
        logging.info("已释放残余的涂抹案子！")
    else:
        sleep(5)

    try:
        logging.info(f"【{program_name}】开始运行")
        photo_mask.main()
    except Exception as e:
        error_logger = logging.getLogger("error")
        error_logger.error(traceback.format_exc())
        if SEND_ERROR_EMAIL:
            send_error_email(program_name, repr(e), traceback.format_exc())
