#!/usr/bin/env python3
"""Debug the trimming logic"""

import cv2
import numpy as np

# Load the voter_id region
region = cv2.imread('/tmp/voter_id_trimmed.png')
print(f"Region size: {region.shape[1]}x{region.shape[0]}")

# Convert to grayscale
gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)

# Check pixel distribution
print(f"\nPixel value stats:")
print(f"  Min: {gray.min()}")
print(f"  Max: {gray.max()}")
print(f"  Mean: {gray.mean():.1f}")

# Dark pixel threshold
dark_threshold = 240

# Scan from right to left
print(f"\nScanning from right to left for dark pixels (< {dark_threshold}):")

rightmost_text = 0
for col in range(gray.shape[1] - 1, max(0, gray.shape[1] - 50), -1):  # Check last 50 columns
    column_pixels = gray[:, col]
    dark_count = np.sum(column_pixels < dark_threshold)

    if col > gray.shape[1] - 10:  # Show last 10 columns
        print(f"  Column {col}: min={column_pixels.min()}, max={column_pixels.max()}, dark_pixels={dark_count}")

    if np.any(column_pixels < dark_threshold):
        rightmost_text = col
        print(f"\n✓ Found dark pixels at column {col}")
        break

if rightmost_text == 0:
    print("\n✗ No dark pixels found!")
else:
    print(f"\nRightmost text at column: {rightmost_text}")
    print(f"Would trim to width: {rightmost_text + 10}")
