from flask import Flask, render_template, request, send_file, abort, jsonify
import numpy as np
import os
import glob
import socket

app = Flask(__name__)

# Placeholder for your numpy arrays
sim_arrays = {
    "self_sim": np.load("/home/minz/temp/gtzan_self_sim_emb.npy"),
    "artist_sim": np.load("/home/minz/temp/gtzan_artist_sim_emb.npy"),
    "album_sim": np.load("/home/minz/temp/gtzan_album_sim_emb.npy"),
}

# Update this list with the full, absolute paths to your audio files
audio_files = glob.glob("/app/suno/minz/datasets/gtzan/audio/*/*.wav")


@app.route("/", methods=["GET", "POST"])
def index():
    return render_template("index.html")


@app.route("/process", methods=["POST"])
def process():
    model = request.form["model"]
    index = int(request.form["index"])

    if model in ["self_sim", "artist_sim", "album_sim"]:
        similarity = sim_arrays[model][index] @ sim_arrays[model].T
        sorted_indices = np.argsort(similarity)[::-1]
        audio_file = audio_files[index] if index < len(audio_files) else None
        return jsonify(
            {
                "model": model,
                "index": index,
                "seed_audio": audio_files[index],
                "sim1": float(similarity[sorted_indices[1]]),
                "sim1_audio": audio_files[sorted_indices[1]],
                "sim2": float(similarity[sorted_indices[2]]),
                "sim2_audio": audio_files[sorted_indices[2]],
                "sim3": float(similarity[sorted_indices[3]]),
                "sim3_audio": audio_files[sorted_indices[3]],
            }
        )
    else:
        abort(400, description="Invalid model selection")


@app.route("/audio_file")
def serve_audio():
    file_path = request.args.get("path")
    if not file_path or not os.path.exists(file_path):
        abort(404, description=f"Audio file not found: {file_path}")

    return send_file(file_path, mimetype="audio/wav")


def get_ip_addresses():
    ip_addresses = []
    try:
        # Get all network interfaces
        interfaces = socket.getaddrinfo(
            host=socket.gethostname(), port=None, family=socket.AF_INET
        )
        for interface in interfaces:
            ip = interface[4][0]
            if not ip.startswith("127."):  # Exclude loopback addresses
                ip_addresses.append(ip)
    except socket.gaierror:
        pass
    return ip_addresses


if __name__ == "__main__":
    print("Server is running on http://127.0.0.1:5000")
    print("Note: This server is only accessible on the local machine.")
    app.run(host="127.0.0.1", port=5000, debug=True)
