#!/usr/bin/env python3
"""Check the 300px voter ID region"""

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

from cells_to_csv import CellsToCSVExtractor

extractor = CellsToCSVExtractor(ocr_engine='google', google_credentials_path='google-credentials.json')

cell_path = 'gogoelocroutput/cells/page003_cell07.png'
cell_color = cv2.imread(cell_path)
cell_gray = cv2.cvtColor(cell_color, cv2.COLOR_BGR2GRAY)
cell_h, cell_w = cell_color.shape[:2]

# Find voter_id template
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 = min(300, cell_w - value_x - 5)
    value_h = label_h + extractor.V_PAD_TOP + extractor.V_PAD_BOTTOM

    print(f"Extracting voter_id region:")
    print(f"  Position: ({value_x}, {value_y})")
    print(f"  Size: {value_w}x{value_h}")

    region = extractor._crop_region(cell_color, value_x, value_y, value_w, value_h)
    cv2.imwrite('/tmp/voter_id_300px.png', region)
    print(f"  Saved to: /tmp/voter_id_300px.png")

    # Test OCR
    from google.cloud import vision
    import os
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'google-credentials.json'
    client = vision.ImageAnnotatorClient()

    _, encoded = cv2.imencode('.png', region)
    image = vision.Image(content=encoded.tobytes())
    response = client.text_detection(image=image)

    if response.text_annotations:
        text = response.text_annotations[0].description.strip()
        print(f"  OCR result: '{text}'")
    else:
        print(f"  OCR result: (empty)")
