import os
import sys
import pandas as pd
import numpy as np
import requests
import json
import yaml
import traceback
import single_case_run
from collections import defaultdict
from pathlib import Path 
root_path = Path(__file__).resolve().parent.parent  
sys.path.append(str(root_path)) 
from models.common import data_process
from models.common import common
from models.common import log 
from config import config
log_path = config.LOG_PATH 
  
logger = log.get_logger(log_path)

def single_case_eval( case_name, mode_label):
    print(f'case_name is {case_name}')
    logger.info(f"[case:{case_name}] SINGLE_CASE_EVAL: Start running...")

    data_path = os.path.join(config.PROCESSED_DATA_PATH, case_name)
    reportPath = config.REPORT_PATH

    case_path = os.path.join(reportPath, case_name)
    if not os.path.exists(case_path):
        os.makedirs(case_path)

    if not os.path.exists(data_path):
        print('Invalid dataPath!')
        logger.error(f"[case:{case_name}] SINGLE_CASE_EVAL: Invalid dataPath!")
        sys.exit(1)
    try:
        logger.info(f"[case:{case_name}] data_precheck: Start running...")
        is_good_data = data_process.data_precheck(data_path, case_name)
        if not is_good_data:
            logger.error(f"[case:{case_name}] Serious data frame loss!")
            sys.exit(-1)
        
    except Exception as e:
        traceback.print_exc()
        logger.error(f"[case:{case_name}] SINGLE_CASE_EVAL: Data processed ERROR: {repr(e)}!", exc_info=True)
        sys.exit(-1)

     # 单用例评价，并生成报告
    try:
        data = data_process.DataPreprocessing(case_name, mode_label)
        case_dict = single_case_run.single_case_run(data, case_name)
        single_case_dict = single_case_run.single_case_statistic(case_dict)  # 对单用例结果增加内容，并生成报告
        
        full_reportPath = os.path.join(case_path, f'{case_name}_single_report.json')
        common.dict2json(single_case_dict, full_reportPath)
    except Exception as e:
        traceback.print_exc()
        logger.error(f"[case:{case_name}] SINGLE_CASE_EVAL: Single case run ERROR: {repr(e)}!", exc_info=True)
        sys.exit(-1)

if __name__ == '__main__':
    mode_label = 'real_car'
    case_name = 1
    single_case_eval(case_name, mode_label)
