"""
Debug visualization to see what the AI detected
"""

import cv2
import json
from pathlib import Path

def visualize_detection(image_path: Path, analysis_json_path: Path, output_path: Path):
    """
    Zeichne Bounding Boxes auf das Bild um zu sehen was die AI erkannt hat
    """
    # Load image
    img = cv2.imread(str(image_path))
    if img is None:
        print(f"❌ Cannot load image: {image_path}")
        return

    # Load analysis
    with open(analysis_json_path, 'r', encoding='utf-8') as f:
        analysis = json.load(f)

    # Draw handwriting regions in RED
    hw_regions = analysis.get('handwriting_regions', [])
    for i, region in enumerate(hw_regions, 1):
        bbox = region.get('bounding_box', {})
        x, y, w, h = bbox.get('x', 0), bbox.get('y', 0), bbox.get('width', 0), bbox.get('height', 0)

        if w > 0 and h > 0:
            # Draw rectangle
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)

            # Draw label
            label = f"HW{i}: {region.get('type')} ({region.get('color_hint')})"
            cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)

    # Draw diagram regions in GREEN
    diagrams = analysis.get('layout', {}).get('diagram_elements', [])
    for i, diagram in enumerate(diagrams, 1):
        bbox = diagram.get('bounding_box', {})
        x, y, w, h = bbox.get('x', 0), bbox.get('y', 0), bbox.get('width', 0), bbox.get('height', 0)

        if w > 0 and h > 0:
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            label = f"DIAGRAM{i}"
            cv2.putText(img, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    # Save
    cv2.imwrite(str(output_path), img)
    print(f"✅ Debug visualization saved: {output_path}")
    print(f"   📍 {len(hw_regions)} handwriting regions (RED)")
    print(f"   📍 {len(diagrams)} diagram regions (GREEN)")

if __name__ == "__main__":
    eingang = Path.home() / "Arbeitsblaetter" / "Eingang"
    bereinigt = Path.home() / "Arbeitsblaetter" / "Bereinigt"

    image_file = "2025-12-11_Auge1.JPG"

    visualize_detection(
        eingang / image_file,
        bereinigt / "2025-12-11_Auge1_analyse.json",
        bereinigt / "2025-12-11_Auge1_DEBUG.jpg"
    )
