import datetime
import os
import sys
import traceback
import uuid
from datetime import date
import pandas as pd
import yaml
from loguru import logger

curr_path = os.path.abspath(os.path.dirname(__file__))
project_root_path = curr_path[:curr_path.find("video_to_word") + len("video_to_word")]
sys.path.append(project_root_path)

from common_func import get_db_engine, mysql_replace_into
from get_material_and_script.get_material_from_kuaishou_kaiyan import GetMaterialFromKuaishouKaiyan
from get_material_and_script.get_material_from_ocean_engine import GetMaterialFromOceanEngine
from get_material_and_script.get_material_from_huichuang import GetMaterialFromHuiChuang


def get_material_and_script():
    # 1 读取配置文件
    with open('/data/pythonProject/video_to_word/config/config.yaml', mode='r', encoding='utf-8') as f:
        config = yaml.load(f.read(), Loader=yaml.FullLoader)

    # 1-1 数据库连接引擎，依据开发环境/生产环境 进行切换
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    if mac in ['5254003fa716', '52540003f5dd']:
        ai_word_engine = get_db_engine(config['ai_word_dev_db'])
    else:
        ai_word_engine = get_db_engine(config['ai_word_product_db'])

    jeecg_boot_engine = get_db_engine(config['jeecg_boot_product_db'])

    # 1-2 分批写入数据库的行数
    chunk_size = config['chunk_size']

    # 1-3 渠道编码&名称
    source_name_map = config['source_name_map']

    # 2 读取查询表得到关键词和渠道
    sql = f"select query_word from ctop_ai_script_query_word_config where end_time = '9999-12-31'"
    df = pd.read_sql(sql, ai_word_engine)
    query_word_lst = list(df['query_word'].unique())
    query_word_time = 3
    for query_word in query_word_lst:
        for source_code, value in source_name_map.items():
            if value['status'] == 1:
                # 任务开始执行
                task_info = {"source_code": source_code,
                             "task_status": "执行中",
                             "query_word": query_word,
                             "script_num": None,
                             "stat_date": datetime.datetime.today().strftime('%Y-%m-%d')}
                task_info_df = pd.DataFrame([task_info])
                task_info_df.to_sql(name='ctop_ai_query_word_task_record',
                                    con=ai_word_engine,
                                    if_exists='append',
                                    index=False,
                                    chunksize=1000,
                                    method=mysql_replace_into)
                try:
                    inst = None
                    # 获取视频信息
                    if source_code == 1:
                        # 获取公司内部的优质素材
                        inst = GetMaterialFromHuiChuang(query_word=query_word,
                                                        logger=logger,
                                                        jeecg_boot_db_engine=jeecg_boot_engine,
                                                        ai_word_db_engine=ai_word_engine)
                        inst.get_video_basic_info()
                    if source_code == 3:
                        # 获取快手开眼快创的优质素材
                        inst = GetMaterialFromKuaishouKaiyan(query_word=query_word,
                                                             logger=logger,
                                                             db_engine=ai_word_engine)
                        inst.get_video_basic_info()
                    if source_code == 2:
                        # 获取头条巨量引擎的优质素材，需要使用参数 query_time_range
                        inst = GetMaterialFromOceanEngine(query_word=query_word,
                                                          period_type=query_word_time,
                                                          logger=logger,
                                                          db_engine=ai_word_engine)
                        inst.get_material_basic_info()
                        if inst.signature_lst:
                            inst.get_video_basic_info()

                    # 获取脚本信息
                    if not inst.video_df.empty:
                        inst.get_script_from_teng_xun_yun()
                        sql = f"select signature from tb_asr_result where signature in" \
                              f" {tuple(inst.video_df.signature.values) if len(inst.video_df) > 1 else tuple(list(inst.video_df.signature.values) * 2)}" \
                              f"and word_text is not null"
                        df = pd.read_sql(sql, ai_word_engine)
                        script_num = len(df)
                    else:
                        script_num = 0
                    # 更新任务执行情况： 执行状态 和 成功的数据量
                    with ai_word_engine.begin() as conn:
                        sql = f"update ctop_ai_query_word_task_record set script_num = {script_num}, task_status = '执行完成', message='执行成功'" \
                              f"where query_word = '{query_word}'" \
                              f"and stat_date = '{datetime.datetime.today().strftime('%Y-%m-%d')}'" \
                              f"and source_code = {source_code}"
                        conn.execute(sql)
                    logger.info(f"查询词：{query_word} 数据来源: {source_code} 日期: {datetime.datetime.today().strftime('%Y-%m-%d')},"
                                f"执行完成获取 {script_num} 条数据")
                except:
                    with ai_word_engine.begin() as conn:
                        sql = f"update ctop_ai_query_word_task_record set  task_status = '执行异常' , message ={traceback.format_exc()}" \
                              f"where query_word = '{query_word}'" \
                              f"and stat_date = '{datetime.datetime.today().strftime('%Y-%m-%d')}'" \
                              f"and source_code = {source_code}"
                        conn.execute(sql)
                    logger.error(f"查询词：{query_word} 数据来源: {source_code} 日期: {datetime.datetime.today().strftime('%Y-%m-%d')},"
                                 f"执行异常: {traceback.format_exc()}")


if __name__ == '__main__':
    logger.remove()
    logger.add("/data/pythonProject/video_to_word/logs/get_high_quality_material.{time:YYYY-MM-DD}.log",
               rotation="00:00",
               format="{time:YYYY-MM-DD HH:mm:ss,SSS} [{process}] [{thread}] {level} {file} {line} - {message}",
               level="INFO")
    try:
        get_material_and_script()
        logger.info(f"{date.today().strftime('%Y-%m-%d')}, 获取素材和脚本任务执行完成.")
    except:
        logger.error(f"{date.today().strftime('%Y-%m-%d')}, 获取素材和脚本任务执行发生异常. {traceback.format_exc()}")
