#!/usr/bin/env python3
"""Debug voter ID region extraction"""

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

from cells_to_csv import CellsToCSVExtractor
import cv2

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

# Test cell
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]

print(f"Cell dimensions: {cell_w}x{cell_h}")

# Find templates
positions = {}
for template_name, template in extractor.templates.items():
    match = extractor.find_template(cell_gray, template)
    if match:
        positions[template_name] = match
        x, y, w, h, score = match
        print(f"\n{template_name:12s}: position ({x}, {y}), size ({w}x{h}), score {score:.3f}")

# Extract voter_id region specifically
if 'voter_id' in positions:
    print("\n" + "="*80)
    print("VOTER ID REGION EXTRACTION")
    print("="*80)

    label_x, label_y, label_w, label_h, score = positions['voter_id']

    # Calculate value region (same logic as in code)
    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"\nLabel position: ({label_x}, {label_y})")
    print(f"Label size: {label_w}x{label_h}")
    print(f"\nValue region calculation:")
    print(f"  value_x = {label_x} + {label_w} + {extractor.H_GAP} = {value_x}")
    print(f"  value_y = {label_y} - {extractor.V_PAD_TOP} = {value_y}")
    print(f"  value_w = {cell_w} - {value_x} - 5 = {value_w}")
    print(f"  value_h = {label_h} + {extractor.V_PAD_TOP} + {extractor.V_PAD_BOTTOM} = {value_h}")

    # Crop and save the region
    region = extractor._crop_region(cell_color, value_x, value_y, value_w, value_h)
    if region is not None:
        cv2.imwrite('/tmp/voter_id_region.png', region)
        print(f"\n✓ Saved voter_id region to: /tmp/voter_id_region.png")
        print(f"  Region size: {region.shape[1]}x{region.shape[0]}")

        # Try OCR on this region
        _, encoded = cv2.imencode('.png', region)
        content = encoded.tobytes()

        from google.cloud import vision
        image = vision.Image(content=content)
        response = extractor.vision_client.text_detection(image=image)

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

        if response.error.message:
            print(f"  Error: {response.error.message}")
    else:
        print("\n✗ Region is None (crop failed)")
