#!/usr/bin/env python3
import sys
sys.path.insert(0, '/Users/guillemhernandezsola/code/manga-translator')

import cv2
import json
import numpy as np

# Import functions from manga-translator.py
import importlib.util
spec = importlib.util.spec_from_file_location("manga_translator", "/Users/guillemhernandezsola/code/manga-translator/manga-translator.py")
mt = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mt)

image_path = '004.png'
detector = mt.MacVisionDetector(source_lang='en')
raw = detector.read(image_path)

# Load current bubbles to see what box 5 contains
with open('bubbles.json') as f:
    bubbles_data = json.load(f)
    box5_data = bubbles_data['5']
    box5_bounds = (box5_data['x'], box5_data['y'], box5_data['x'] + box5_data['w'], box5_data['y'] + box5_data['h'])
    print(f'Box 5 bounds (xyxy): {box5_bounds}')
    print()

# Print all detections sorted by position
print('All raw detections:')
for i, (bbox, text, conf) in enumerate(sorted(raw, key=lambda x: (mt.quad_bbox(x[0])[1], mt.quad_bbox(x[0])[0]))):
    b = mt.quad_bbox(bbox)
    t_norm = mt.normalize_text(text)
    print(f'{i:2d}. [{b[0]:3d},{b[1]:3d} -> {b[2]:3d},{b[3]:3d}] conf={conf:.2f} text="{t_norm}"')
    
    # Check if this overlaps with box 5
    b5_x1, b5_y1, b5_x2, b5_y2 = box5_bounds
    if not (b[2] < b5_x1 or b[0] > b5_x2 or b[3] < b5_y1 or b[1] > b5_y2):
        print(f'  ^ OVERLAPS with Box 5!')
