#!/usr/bin/env python3
"""Check the trimmed 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'
page_num, cell_num = 3, 7

regions, positions, cell_color, cell_dims = extractor.extract_regions_for_batch(cell_path, page_num, cell_num)

print(f"Total regions extracted: {len(regions)}")

# Find and save voter_id region
for region_data, region_id in regions:
    if 'voter_id' in region_id:
        print(f"\nVoter ID region:")
        print(f"  Region ID: {region_id}")
        print(f"  Size: {region_data.shape[1]}x{region_data.shape[0]}")

        cv2.imwrite('/tmp/voter_id_trimmed.png', region_data)
        print(f"  Saved to: /tmp/voter_id_trimmed.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_data)
        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)")

        break
