import json
import math
import argparse

def calculate_distance(point1, point2):
    """Berechnet den euklidischen Abstand zwischen zwei 3D-Punkten."""
    return math.sqrt(sum([(a - b) ** 2 for a, b in zip(point1, point2)]))

def analyze_marker_detection(detected_markers_file, original_markers_file):
    """Analysiert die Markererkennung und gibt Erkennungsrate und Genauigkeit aus."""

    with open(detected_markers_file, 'r') as f:
        detected_data = json.load(f)

    with open(original_markers_file, 'r') as f:
        original_data = json.load(f)

    detected_marker_ids = {marker['marker_id'] for marker in detected_data['markers']}
    original_marker_ids = {marker['id'] for marker in original_data}

    # Erkannte und nicht erkannte Marker
    recognized_markers = len(detected_marker_ids.intersection(original_marker_ids))
    missing_markers = len(original_marker_ids.difference(detected_marker_ids))
    
    # Distanzen berechnen
    distances = []
    for original_marker in original_data:
        marker_id = original_marker['id']
        
        # Gefundener Marker suchen
        detected_marker = next((m for m in detected_data['markers'] if m['marker_id'] == marker_id), None)
        
        if detected_marker:
            distance = calculate_distance(original_marker['position_m'], detected_marker['position_m'])
            distances.append(distance)

    if not distances:
        print("Keine gemeinsamen Marker gefunden, um die Genauigkeit zu bewerten.")
        return

    # Statistiken berechnen
    distances.sort()
    mean_distance = sum(distances) / len(distances)
    
    # 90%-Radius
    n = len(distances)
    index_90 = int(0.9 * n) - 1
    radius_90 = distances[index_90]

    # 80%-Radius
    index_80 = int(0.8 * n) - 1
    radius_80 = distances[index_80]

    # Schlechtester Abstand
    worst_distance = distances[-1]

    print(f"Erkannte Marker: {recognized_markers}")
    print(f"Nicht erkannte Marker: {missing_markers}")
    print(f"Gesamtzahl der Original-Marker: {len(original_marker_ids)}")
    print(f"Erkennungsrate: {recognized_markers / len(original_marker_ids) * 100:.2f}%")
    print(f"Gemittelter 3D-Abstand: {mean_distance:.4f}m")
    print(f"90%-Radius: {radius_90:.4f}m")
    print(f"80%-Radius: {radius_80:.4f}m")
    print(f"Schlechtester Abstand: {worst_distance:.4f}m")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Analysiert die Markererkennung.")
    parser.add_argument("detected_file", help="Pfad zur JSON-Datei mit den erkannten Markern.")
    parser.add_argument("original_file", help="Pfad zur JSON-Datei mit den originalen Markern.")
    args = parser.parse_args()

    analyze_marker_detection(args.detected_file, args.original_file)