import argparse
import json
import os
import pandas as pd
import shutil
from PIL import Image, ImageDraw, ImageFont

parser = argparse.ArgumentParser()
parser.add_argument('--task_root_dir',type=str,required=True, help='待检测任务的根目录')
# 解析命令行参数
args = parser.parse_args()

def generate_excel(video_report_path):
    rule_header = None
    rule_rows = []
    page_name = []
    data = json.load(open(video_report_path,'r'))

    for page in data:
        page=data[page]
        print(page)
        video_path = page["合成视频路径"]
        if rule_header is None:
            rule_header=page["判断条目"]
        result = page["通过情况"]
        page_name.append(os.path.splitext(os.path.basename(video_path))[0])
        rule_rows.append(result)

    df = pd.DataFrame(rule_rows, columns=rule_header)
    new_df = pd.DataFrame()
    for col in df.columns:
        new_df[f'{col}_预测'] = df[col]
        new_df[f'{col}_真实'] = None
    new_df.insert(0,'页面编号',page_name)
    new_df.to_excel('app_video_report.xlsx', index=False)

    
def run(task_root_dir):
    
    video_report_path = os.path.join(task_root_dir,'app_video_report.json')
    # 生成excel
    generate_excel(video_report_path)

    output_img_path = 'temp.mp4'
    data = json.load(open(video_report_path,'r'))
    for page in data:
        page=data[page]
        video_path = page["合成视频路径"]
        index = video_path.find('videos')
        if index != -1:
            # 提取 'videos' 及其之后的内容
            video_path = video_path[index:]
        shutil.copy(os.path.join(task_root_dir,video_path),output_img_path)
        rule_header=page["判断条目"]
        result = page["通过情况"]
        result_map = [[rule_header[i],result[i]]for i in range(len(rule_header))]
        user_input = input("请输入 'n' 继续遍历下一个，输入 'c' 结束遍历: ")
        if user_input == 'c':
            print("程序已结束。")
            return 0
        elif user_input == 'n':
            print(f"视频展示在: {output_img_path}")
            print(f"原视频地址: {video_path}")
            print(f"该视频对应检测结果: {result_map}")

        else:
            print("输入无效，请输入 'n' 或 'c'。")
if __name__=="__main__":
    task_root_dir = args.task_root_dir
    run(task_root_dir)