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

import cv2
import numpy as np
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)
image = cv2.imread(image_path)

# Full filtering
filtered = []
for bbox, text, conf in raw:
    t = mt.normalize_text(text)
    qb = mt.quad_bbox(bbox)
    
    if conf < 0.12 or len(t) < 1 or mt.is_noise_text(t) or mt.is_sound_effect(t) or mt.is_title_text(t):
        continue
    if qb[1] < int(image.shape[0] * mt.TOP_BAND_RATIO):
        if conf < 0.70 and len(t) >= 5:
            continue
    
    filtered.append((bbox, t, conf))

# Get grouping
bubbles, bubble_boxes, bubble_quads, bubble_indices = mt.group_tokens(
    filtered, image.shape, gap_px=mt.auto_gap(image_path), bbox_padding=3
)

print("=== TESTING PANEL SPLIT ON BUBBLE 7 ===\n")

bid = 7
box = bubble_boxes[bid]
print(f"Bubble {bid} box: {box}")
print(f"Bubble {bid} quads: {len(bubble_quads[bid])}")
print(f"Bubble {bid} indices: {len(bubble_indices[bid])}")

# Test split_panel_box
split_result = mt.split_panel_box(image, box, bubble_quads=bubble_quads[bid])

if split_result:
    box_left, box_right, split_x = split_result
    print(f"\n✓ Panel split detected!")
    print(f"  Split X: {split_x}")
    print(f"  Left box: {box_left}")
    print(f"  Right box: {box_right}")
    
    # Simulate index split
    left_idxs, right_idxs = [], []
    for idx in bubble_indices[bid]:
        cx, cy = mt.quad_center(filtered[idx][0])
        if cx < split_x:
            left_idxs.append(idx)
        else:
            right_idxs.append(idx)
    
    print(f"\n  Left indices ({len(left_idxs)}): {left_idxs}")
    print(f"  Right indices ({len(right_idxs)}): {right_idxs}")
    
    if left_idxs and right_idxs:
        print(f"\n✓ Split is valid (both sides have content)")
    else:
        print(f"\n✗ Split is invalid (one side is empty)")
else:
    print(f"\n✗ No panel split detected")
    print(f"  Threshold would be: quads >= 10? {len(bubble_quads[bid]) >= 10}")
    print(f"  Width >= 50? {box[2] - box[0] >= 50}")
    print(f"  Height >= 50? {box[3] - box[1] >= 50}")
