# compare_images.py
import sys
import json
from skimage.metrics import structural_similarity as ssim
from PIL import Image
import numpy as np

def compare_images(drawing_path, reference_path):
    try:
        # Cargar imágenes en escala de grises
        img1 = Image.open(drawing_path).convert('L')
        img2 = Image.open(reference_path).convert('L')

        # Redimensionar para igualar tamaños
        img1 = img1.resize((300, 300))
        img2 = img2.resize((300, 300))

        # Convertir a arrays numpy
        img1 = np.array(img1)
        img2 = np.array(img2)

        # Calcular la similitud estructural
        score, _ = ssim(img1, img2, full=True)
        return round(score * 100, 2)

    except Exception as e:
        return str(e)

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print(json.dumps({"success": False, "error": "Faltan parámetros en la ejecución."}))
        sys.exit(1)

    drawing_path = sys.argv[1]
    reference_path = sys.argv[2]

    score = compare_images(drawing_path, reference_path)
    print(json.dumps({"success": True, "score": score}))
