#!/usr/bin/env python3
"""Check cell 8 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_cell08.png'
page_num, cell_num = 3, 8

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

# Find voter_id region
for region_data, region_id in regions:
    if 'voter_id' in region_id:
        print(f"Voter ID region size: {region_data.shape[1]}x{region_data.shape[0]}")
        cv2.imwrite('/tmp/cell8_voter_id.png', region_data)
        print(f"Saved to: /tmp/cell8_voter_id.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
