
from pymediainfo import MediaInfo
from datetime import datetime
import json
from utils.db import insert_sca_video,insert_sca_video_details
from collections import Counter

def getVideoResolution(file_path):
    media_info = MediaInfo.parse(file_path)  # 解析视频文件
    
    for track in media_info.tracks:
        if track.track_type == 'Video': 
            return track.width,track.height

def get_type_name_by_id(id):
    type_dict = {
        0: "正茧",
        1: "双宫茧",
        2: "黄斑茧",
        3: "毛茧",
        4: "蛆壳茧",
    }
    return type_dict.get(id, "未知类型")

# 将视频信息保存至数据库
def save_sca_results(file_path, out_put_file_name,tracker_dict,
                     analysis_time,statics =[]):
    media_info = MediaInfo.parse(file_path)  # 解析视频文件
    video_data = {}  # 用于存储视频信息
    
    for track in media_info.tracks:
        if track.track_type == 'General': 
            video_data.update({
                "v_file_name": track.file_name_extension,
                "v_duration": round(track.duration / 1000),
                "v_size": round(track.file_size/1024,2), 
                "v_video_codec": track.video_format_list,
                "v_audio_codec": track.audio_codecs,
                "v_overall_bit_rate": track.overall_bit_rate,  
            })
        if track.track_type == 'Video': 
            video_data.update({
                "v_resolution":  f"{track.width}x{track.height}" 
            })

    # 分析 得出数量最多的种类 以及 出现次多的种类
    counter = Counter(tracker_dict.values())     # 统计所有 value 的出现次数
    most_common = counter.most_common(2)  # 取出现次数前两名（返回列表）
    primary_type = get_type_name_by_id(most_common[0][0]) if most_common else ""
    secondary_type = get_type_name_by_id(most_common[1][0]) if len(most_common) > 1 else ""

      # 1️⃣ 统计 { value: count }
    count_map = {}
    for k, v in tracker_dict.items():
        v_int = int(v)
        count_map[v_int] = count_map.get(v_int, 0) + 1

    # 2️⃣ 替换成类型名称
    result = {}
    for type_value, count in count_map.items():
        type_name = get_type_name_by_id(type_value)
        result[type_name] = count

    other_info = result

    # 分析结果进行统计 得出 单帧最大蚕茧数量
    max_count_in_same_frame = 0
    for timestamp_in_video,json in statics.items():
        count_in_frame = sum(json.values())
        if count_in_frame > max_count_in_same_frame:
            max_count_in_same_frame = count_in_frame

    # 保存至数据库
    video_id = insert_sca_video(
        # 取后八位
        name=out_put_file_name.split('/')[-1].split('.')[0].replace('-','')[-8:],
        raw_object_name=video_data.get("v_file_name", "").split('/')[-1],
        ai_object_name=out_put_file_name.split('/')[-1],
        duration=video_data.get("v_duration", 0),
        size=video_data.get("v_size", 0),
        video_codec=video_data.get("v_video_codec", ""),
        audio_codec=video_data.get("v_audio_codec", ""),
        overall_bit_rate=video_data.get("v_overall_bit_rate", 0),
        resolution=video_data.get("v_resolution", ""),
        sc_analysis_time= analysis_time,
        sc_analysis_total_count=len(tracker_dict),
        sc_analysis_max_count=max_count_in_same_frame,
        sc_analysis_primary_type= primary_type,
        sc_analysis_secondary_type= secondary_type,
        other_info= other_info,
    )

    # 将细则存入数据库
    counter = Counter()

    for timestamp_in_video, json in statics.items():
        insert_sca_video_details(video_id,timestamp_in_video, json)