#!/usr/bin/env python3
"""Check cell 11"""

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_cell11.png'
page_num, cell_num = 3, 11

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

print(f"Total regions: {len(regions)}")
print(f"Templates found: {list(positions.keys())}")

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

        # Save original
        cv2.imwrite('/tmp/cell11_voter_id_orig.png', region_data)

        # Save enhanced
        enhanced = extractor._enhance_for_ocr(region_data)
        cv2.imwrite('/tmp/cell11_voter_id_enhanced.png', enhanced)

        print(f"  Saved original to: /tmp/cell11_voter_id_orig.png")
        print(f"  Saved enhanced to: /tmp/cell11_voter_id_enhanced.png")

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

        # Test original
        _, 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 (original): '{text}'")
        else:
            print(f"  OCR (original): (empty)")

        # Test enhanced
        _, encoded = cv2.imencode('.png', enhanced)
        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 (enhanced): '{text}'")
        else:
            print(f"  OCR (enhanced): (empty)")

        break
