from pathlib import Path
from typing import Tuple, List, Optional, Any

import pandas as pd
import numpy as np

from music_engine.matcher import MusicMatcher
from music_engine.image_processor import ImageProcessor

BASE_DIR = Path(__file__).resolve().parent

def load_music_engine() -> MusicMatcher:
    #Инициализация модуля подбора музыкальных композиций.
    db_path = BASE_DIR.parent / "dataset" / "DEAM" / "music_db.csv"
    model_path = BASE_DIR / "music_engine" / "va_regressor.pkl"
    
    return MusicMatcher(db_path=db_path, model_path=model_path)

def load_image_processor() -> ImageProcessor:
    #Инициализация модуля экстракции визуальных признаков.
    weights_path = BASE_DIR / "emoset_resnet50_best.pth"
    
    return ImageProcessor(weights_path)

def load_emoset_data() -> Tuple[Optional[List[str]], Optional[np.ndarray], Optional[np.ndarray], Optional[Path]]:
    # Загрузка тестовой выборки датасета EmoSet.
    # Модуль сохранен для обеспечения обратной совместимости в отладочном контуре.
    try:
        images_path = BASE_DIR.parent / "dataset" / "EmoSet-118K" / "test" / "images"
        labels_path = BASE_DIR / "emoset_test_labels.npy"
        embeddings_path = BASE_DIR / "emoset_test_embeddings.npy"
        
        if not all(p.exists() for p in [labels_path, embeddings_path]):
            return None, None, None, None
            
        labels = np.load(labels_path)
        embeddings = np.load(embeddings_path)
        
        csv_path = BASE_DIR.parent / "dataset" / "EmoSet-118K" / "test" / "labels.csv"
        df = pd.read_csv(csv_path)
        
        return df['filename'].tolist(), embeddings, labels, images_path
        
    except Exception as e:
        print(f"[WARN] Failed to load EmoSet test artifacts: {str(e)}")
        return None, None, None, None