# -*- coding: utf-8 -*-

"""
Basic logger: custom color logger
"""
try:
    from custom_logger.main_log import vactor_logger as log
except ImportError:
    import logging as log; log.basicConfig(level=log.DEBUG)

"""
Package: standard
"""
import numpy as np
import matplotlib.pyplot as plt
import os

from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from PIL import Image 
from dataclasses import dataclass
import matplotlib
matplotlib.use('Agg')

"""
Package: 3rd party
"""

"""
Package: custom
"""
from custom_apps.FEATURE_VECTOR_SIMILARITY_FAISS.const import *
from custom_apps.FEATURE_VECTOR_SIMILARITY_FAISS.faiss_similarity_search import FEMUsageInfo

"""
Definition
"""
@dataclass
class ReportInfo:
    feature_extraction_model : str
    model_architecture : str
    train_model : str
    feature_extraction_time : str
    
    query_image_path : str
    result_image_paths: list
    result_percents: list
    similarity_type: str


"""
Implementation
"""

def table_setting(report_info:ReportInfo, result_image_path):
    """
    결과 정보를 테이블 형태로 시각화하여 이미지로 저장하는 함수
    """
    
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(1920/100, 1080/100), dpi=100) # 2행 1열 서브플롯
    
    ##====================info table (상단 테이블)
    _info_table_row = [ReportInfoConst.feature_extraction_model,
                       ReportInfoConst.model_architecture,
                       ReportInfoConst.train_model,
                       ReportInfoConst.feature_extraction_time,
                       ReportInfoConst.similarity_type]
    _info_table_data = [[report_info.feature_extraction_model],
                       [report_info.model_architecture],
                       [report_info.train_model],
                       [report_info.feature_extraction_time],
                       [report_info.similarity_type]]
    ax1.set_axis_off() # 축 숨기기
    info_table = ax1.table(cellText=_info_table_data,
                   rowLabels=_info_table_row, 
                   loc='center',
                   cellLoc='left',
                   bbox=[0,0,0.8,1])
    # info_table.auto_set_column_width(True) # 열 너비를 내용에 맞게 자동 조절
    # info_table.scale(0.8, 1.0)
    info_table.set_fontsize(20) # 폰트
    
    for (row, col), cell in info_table.get_celld().items():
        cell.set_height(0.15)
    ##================================
    
    ##====================result table (하단 테이블)
    _result_table_col = [ReportInfoConst.query, ReportInfoConst.result, ReportInfoConst.result, ReportInfoConst.result, ReportInfoConst.result]
    _result_table_data = [['','','','',''],
                       ['Similarity Rate(%)',
                        report_info.result_percents[0],
                        report_info.result_percents[1],
                        report_info.result_percents[2],
                        report_info.result_percents[3]]]
    
    ax2.set_axis_off() # 축 숨기기
    result_table = ax2.table(cellText=_result_table_data,
                   colLabels=_result_table_col, 
                   loc='center',
                   cellLoc='center',
                   bbox=[-0.23,0,1.2,0.8])
    result_table.set_fontsize(20) # 폰트
    
    for (row, col), cell in result_table.get_celld().items():
        if row == 1:
            cell.set_height(0.5)
        else:  
            cell.set_height(0.15)
    
    # 이미지 삽입 - 위치 보정하여 셀 가운데 정렬
    image_paths = [report_info.query_image_path] + report_info.result_image_paths[:4]
    target_size = (240, 180)
    for col, img_path in enumerate(image_paths):
        try:
            img = Image.open(img_path).convert("RGB").resize(target_size)
            img_array = np.asarray(img)

            imagebox = OffsetImage(img_array, zoom=1.0)
            position_x = -0.13 + 0.24 * col  # 열 중심 (0.1, 0.3, 0.5, 0.7, 0.9)
            position_y = 0.4         # 테이블 세로 가운데 살짝 위쪽
            
            ab = AnnotationBbox(imagebox,
                                (position_x, position_y),
                                frameon=False,
                                box_alignment=(0.4, 0.5),
                                xycoords='axes fraction') 
            ax2.add_artist(ab)
        except Exception as e:
            print(f"[이미지 로딩 실패] {img_path}: {e}")

    plt.tight_layout()
    plt.savefig(result_image_path)
