#!/usr/bin/env python3
"""
Manual printer tracking dot pattern detection and visualization
"""
from PIL import Image, ImageDraw
import numpy as np

def find_dot_grid(image_path="Zard - Copy.jpg"):
    """Try to find and visualize potential tracking dot grids"""
    print(f"Searching for dot grid patterns in {image_path}...")
    
    img = Image.open(image_path)
    img_array = np.array(img)
    
    if len(img_array.shape) == 3:
        r = img_array[:,:,0].astype(float)
        g = img_array[:,:,1].astype(float)
        b = img_array[:,:,2].astype(float)
        
        # Calculate yellow channel
        yellow = (r + g - 2*b) / 4
        
        # Find potential dots (top percentile)
        threshold = np.percentile(yellow, 99)
        dots_mask = yellow > threshold
        
        # Get coordinates
        y_coords, x_coords = np.where(dots_mask)
        
        print(f"Found {len(x_coords)} potential dot pixels")
        
        if len(x_coords) > 0:
            # Create visualization
            viz = img.copy()
            draw = ImageDraw.Draw(viz)
            
            # Mark all potential dot pixels
            for x, y in zip(x_coords[:5000], y_coords[:5000]):  # Limit for visualization
                draw.rectangle([x-2, y-2, x+2, y+2], outline='red', width=1)
            
            viz.save("dot_visualization.png")
            print(f"Saved visualization to: dot_visualization.png")
            
            # Try to find grid spacing
            print("\nAnalyzing spatial distribution...")
            
            # Look at first 1000 dots to find spacing
            if len(x_coords) > 100:
                sample_x = sorted(x_coords[:1000])
                sample_y = sorted(y_coords[:1000])
                
                # Calculate differences between consecutive dots
                x_diffs = []
                y_diffs = []
                
                for i in range(len(sample_x) - 1):
                    diff = sample_x[i+1] - sample_x[i]
                    if 5 < diff < 200:  # Reasonable range for dot spacing
                        x_diffs.append(diff)
                
                for i in range(len(sample_y) - 1):
                    diff = sample_y[i+1] - sample_y[i]
                    if 5 < diff < 200:
                        y_diffs.append(diff)
                
                if x_diffs:
                    # Find most common spacing
                    x_diffs_array = np.array(x_diffs)
                    hist, bins = np.histogram(x_diffs_array, bins=50)
                    most_common_x = bins[np.argmax(hist)]
                    print(f"Most common X spacing: ~{most_common_x:.1f} pixels")
                
                if y_diffs:
                    y_diffs_array = np.array(y_diffs)
                    hist, bins = np.histogram(y_diffs_array, bins=50)
                    most_common_y = bins[np.argmax(hist)]
                    print(f"Most common Y spacing: ~{most_common_y:.1f} pixels")
                
                # Try to find a regular grid
                print("\nSearching for grid pattern...")
                # Look in a small region
                region_size = 300
                region = yellow[:region_size, :region_size]
                region_dots = region > np.percentile(region, 99)
                region_y, region_x = np.where(region_dots)
                
                if len(region_x) > 10:
                    print(f"In top-left {region_size}x{region_size} region: {len(region_x)} dots")
                    
                    # Save region visualization
                    region_viz = Image.fromarray((region / region.max() * 255).astype(np.uint8))
                    region_viz = region_viz.convert('RGB')
                    region_viz = region_viz.resize((region_size*3, region_size*3), Image.NEAREST)
                    draw_region = ImageDraw.Draw(region_viz)
                    
                    for x, y in zip(region_x, region_y):
                        draw_region.ellipse([x*3-3, y*3-3, x*3+3, y*3+3], fill='red')
                    
                    region_viz.save("region_dots_zoom.png")
                    print(f"Saved zoomed region to: region_dots_zoom.png")

if __name__ == "__main__":
    find_dot_grid()
