#!/usr/bin/env python3
"""Compare extracted region vs Google Vision's bounding box"""

import cv2
import os
import sys
sys.path.insert(0, 'workflow')

from cells_to_csv import CellsToCSVExtractor
from google.cloud import vision

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'google-credentials.json'
client = vision.ImageAnnotatorClient()

# Load cell
cell = cv2.imread('gogoelocroutput/cells/page003_cell07.png')

# Get full OCR
_, encoded = cv2.imencode('.png', cell)
image = vision.Image(content=encoded.tobytes())
response = client.text_detection(image=image)

# Find voter ID block
voter_id_block = None
for annotation in response.text_annotations[1:]:
    if '৬৮০' in annotation.description or '680' in annotation.description:
        vertices = [(v.x, v.y) for v in annotation.bounding_poly.vertices]
        print(f"Found voter ID block: '{annotation.description}'")
        print(f"  Bounding box: {vertices}")

        # Calculate bbox
        xs = [v[0] for v in vertices]
        ys = [v[1] for v in vertices]
        print(f"  X range: {min(xs)} to {max(xs)} (width: {max(xs)-min(xs)})")
        print(f"  Y range: {min(ys)} to {max(ys)} (height: {max(ys)-min(ys)})")

        voter_id_block = annotation
        break

# Now compare with our extraction
extractor = CellsToCSVExtractor(ocr_engine='google', google_credentials_path='google-credentials.json')

cell_gray = cv2.cvtColor(cell, cv2.COLOR_BGR2GRAY)
cell_h, cell_w = cell.shape[:2]

positions = {}
for template_name, template in extractor.templates.items():
    match = extractor.find_template(cell_gray, template)
    if match:
        positions[template_name] = match

if 'voter_id' in positions:
    label_x, label_y, label_w, label_h, _ = positions['voter_id']

    value_x = label_x + label_w + extractor.H_GAP
    value_y = label_y - extractor.V_PAD_TOP
    value_w = cell_w - value_x - 5
    value_h = label_h + extractor.V_PAD_TOP + extractor.V_PAD_BOTTOM

    print(f"\nOur extraction:")
    print(f"  X range: {value_x} to {value_x + value_w} (width: {value_w})")
    print(f"  Y range: {value_y} to {value_y + value_h} (height: {value_h})")

    if voter_id_block:
        vertices = [(v.x, v.y) for v in voter_id_block.bounding_poly.vertices]
        xs = [v[0] for v in vertices]
        ys = [v[1] for v in vertices]

        print(f"\nComparison:")
        print(f"  Google's X start: {min(xs)}, Our X start: {value_x} (diff: {value_x - min(xs)})")
        print(f"  Google's Y start: {min(ys)}, Our Y start: {value_y} (diff: {value_y - min(ys)})")
        print(f"  Google's width: {max(xs)-min(xs)}, Our width: {value_w}")
        print(f"  Google's height: {max(ys)-min(ys)}, Our height: {value_h}")
