#!/usr/bin/env python3
import run_phi           # so we can grab the real relevance classes
import __main__          # our loader is run as __main__
# alias the pickled classes into __main__ 
for cls in ("PhiRelevance", "GMMRelevance", "KDERelevance", "HistRelevance"):
    setattr(__main__, cls, getattr(run_phi, cls))

import pickle
import sys
import os
import numpy as np
import pandas as pd

def returnPickle():
    # === Select Pickle File ===
    available_pickles = [f for f in os.listdir("phi_pickles") if f.endswith(".pkl")]
    if not available_pickles:
        print("No pickle files found in 'phi_pickles'.")
        sys.exit(1)

    print("Available methods found in phi_pickles:")
    for i, fn in enumerate(available_pickles, 1):
        print(f"  {i}. {fn}")

    choice = input("Select method number or name: ").strip().lower()
    if choice.isdigit() and 1 <= int(choice) <= len(available_pickles):
        selected = available_pickles[int(choice) - 1]
    elif choice in available_pickles:
        selected = choice
    else:
        print("Invalid selection.")
        sys.exit(1)

    file_path = os.path.join("phi_pickles", selected)
    try:
        with open(file_path, "rb") as f:
            data = pickle.load(f)
        print(f"\nLoaded φ-model from: {file_path} (method={data.get('method')})")
    except Exception as e:
        print(f"Error loading pickle: {e}")
        sys.exit(1)

    # Extract relevance callable
    relevance = data.get("relevance")
    if not callable(relevance):
        print("ERROR: 'relevance' function missing or not callable.")
        sys.exit(1)

    # Choose input source
    print("\nChoose input source:")
    print("  1. Manually enter values")
    print("  2. Load from CSV column")
    choice = input("Enter choice (1 or 2): ").strip()
    if choice == "1":
        raw = input("Enter comma-separated values (e.g. 100,200,300): ")
        try:
            y_new = np.array([float(x) for x in raw.split(",")])
        except ValueError:
            print("Invalid numeric input.")
            sys.exit(1)
    elif choice == "2":
        csv_path = input("Enter path to CSV file: ").strip()
        try:
            df = pd.read_csv(csv_path)
            y_new = df.iloc[:, -1].dropna().astype(float).values
        except Exception as e:
            print(f"Error reading CSV: {e}")
            sys.exit(1)
    else:
        print("Invalid choice.")
        sys.exit(1)

    # Query relevance
    print("\nRelevance Scores:")
    for val in y_new:
        try:
            score = relevance(val)
            print(f"  y = {val:.4f} --> φ = {score:.6f}")
        except Exception as e:
            print(f"  y = {val:.4f} --> Error: {e}")

if __name__ == "__main__":
    returnPickle()