# -*- coding: utf-8 -*-
"""
@File: services.py
@Date: 2020-09-14
@author: A2TEC
@section MODIFYINFO 수정정보
- 수정자/수정일   : 수정내역
- 2022-01-14/hsj100@a2tec.co.kr : refactoring
@brief: services api
"""

import requests, json, traceback, os
from fastapi import APIRouter, Depends, Body
from starlette.requests import Request
from typing import Annotated, List

from vector_rest.app.common import consts
from vector_rest.app import models as M
from vector_rest.app.utils.date_utils import D
from custom_logger.vactor_log import vactor_logger as LOG

from custom_apps.faiss_imagenet.main import search_idxs
from custom_apps.FEATURE_VECTOR_SIMILARITY_FAISS.faiss_functions import get_clip_info, save_report_image, get_models

from custom_apps.FEATURE_VECTOR_SIMILARITY_FAISS.faiss_similarity_search import FEMUsageInfo

router = APIRouter(prefix="/services")


@router.post("/faiss/vector/search/imagenet", summary="imagenet search", response_model=M.ResponseBase)
async def vactor_search(request: Request, request_body_info: M.VactorSearchReq):
    """
    ## 벡터검색
    
    ## 정보
    > 
    
    """
    response = M.ResponseBase()
    try:
        LOG.info(request_body_info.query_image_path)
        if os.path.exists(request_body_info.query_image_path):
            search_idxs(image_path=request_body_info.query_image_path, 
                        index_type=request_body_info.index_type, 
                        search_num=request_body_info.search_num)
        else:
            raise Exception(f"File {request_body_info.query_image_path} does not exist.")
        
        return response.set_message()
       
    except Exception as e:
        LOG.error(traceback.format_exc())
        return response.set_error(e)
    

@router.post("/faiss/vector/search/vit/report", summary="vit search report", response_model=M.ResponseBase)
async def vactor_report_vit(request: Request, request_body_info: M.VactorSearchVitReportReq):
    """
    이미지 경로를 입력받아 repport image 저장
    """
    response = M.ResponseBase()
    try:
        if not os.path.exists(request_body_info.query_image_path):
            raise FileNotFoundError(f"File {request_body_info.query_image_path} does not exist.")
        
        model = get_models(index_type=request_body_info.index_type, model_type=request_body_info.model_type)
        
        report_info = get_clip_info(model,request_body_info.query_image_path)
        save_report_image(report_info, request_body_info.report_path)
        
        return response.set_message()
       
    except Exception as e:
        LOG.error(traceback.format_exc())
        return response.set_error(e)
    

@router.post("/faiss/vector/search/vit", summary="vit search", response_model=M.VactorSearchVitRes)
async def vactor_vit(request: Request, request_body_info: M.VactorSearchVitReq):
    """
    이미지 경로 를 입력받아 vit 방식으로 검색
    """
    response = M.VactorSearchVitRes()
    try:
        if not os.path.exists(request_body_info.query_image_path):
            raise FileNotFoundError(f"File {request_body_info.query_image_path} does not exist.")
        
        model = get_models(index_type=request_body_info.index_type, model_type=request_body_info.model_type)
        
        report_info = get_clip_info(model,request_body_info.query_image_path,top_k=request_body_info.search_num)
        
        return response.set_message({
            'result_image_paths': report_info.result_image_paths,
            'result_percents': report_info.result_percents
        })
       
    except Exception as e:
        LOG.error(traceback.format_exc())
        return response.set_error(e)