#!/usr/bin/env python3
"""
Analyze the exact dot positions to understand the pattern
"""
from PIL import Image, ImageDraw
import numpy as np
from collections import Counter

# Load the dots image
img = Image.open('yd_Zard_uncompressed_dots.png')
arr = np.array(img)

# Focus on the region with dots
x_min, x_max = 3400, 4020
y_min, y_max = 1000, 1640

region = arr[y_min:y_max, x_min:x_max]

# Find all dots
threshold = 200
dots_mask = region > threshold
y_coords, x_coords = np.where(dots_mask)

print(f"Total dots found: {len(x_coords)}")
print(f"\nX coordinates: min={x_coords.min()}, max={x_coords.max()}")
print(f"Y coordinates: min={y_coords.min()}, max={y_coords.max()}")

# Analyze X positions - find clusters
x_sorted = np.sort(x_coords)
x_unique = []
current_cluster = [x_sorted[0]]

for i in range(1, len(x_sorted)):
    if x_sorted[i] - x_sorted[i-1] < 5:  # Same cluster
        current_cluster.append(x_sorted[i])
    else:  # New cluster
        x_unique.append(int(np.mean(current_cluster)))
        current_cluster = [x_sorted[i]]

if current_cluster:
    x_unique.append(int(np.mean(current_cluster)))

print(f"\nUnique X positions (columns): {len(x_unique)}")
print(f"X positions: {x_unique}")

# Analyze Y positions - find clusters
y_sorted = np.sort(y_coords)
y_unique = []
current_cluster = [y_sorted[0]]

for i in range(1, len(y_sorted)):
    if y_sorted[i] - y_sorted[i-1] < 5:  # Same cluster
        current_cluster.append(y_sorted[i])
    else:  # New cluster
        y_unique.append(int(np.mean(current_cluster)))
        current_cluster = [y_sorted[i]]

if current_cluster:
    y_unique.append(int(np.mean(current_cluster)))

print(f"\nUnique Y positions (rows): {len(y_unique)}")
print(f"Y positions: {y_unique}")

# Create grid based on actual positions
if len(x_unique) > 0 and len(y_unique) > 0:
    print(f"\n{'='*70}")
    print(f"ACTUAL DOT GRID ({len(y_unique)} rows x {len(x_unique)} columns):")
    print(f"{'='*70}")
    
    # Create a set of dot positions for quick lookup
    dot_positions = set()
    for x, y in zip(x_coords, y_coords):
        # Find closest cluster center
        x_cluster = min(x_unique, key=lambda xc: abs(xc - x))
        y_cluster = min(y_unique, key=lambda yc: abs(yc - y))
        dot_positions.add((y_cluster, x_cluster))
    
    # Print grid
    print("     " + "".join(f"{i%10}" for i in range(len(x_unique))))
    for row_idx, y_pos in enumerate(y_unique):
        row_str = f"R{row_idx:2d}: "
        for x_pos in x_unique:
            if (y_pos, x_pos) in dot_positions:
                row_str += "█"
            else:
                row_str += "·"
        print(row_str)
    
    # Try to decode if it looks like a standard 15x8 or similar grid
    print(f"\n{'='*70}")
    print("ATTEMPTING DECODE:")
    print(f"{'='*70}")
    
    # Create a binary grid
    grid = np.zeros((len(y_unique), len(x_unique)), dtype=int)
    for row_idx, y_pos in enumerate(y_unique):
        for col_idx, x_pos in enumerate(x_unique):
            if (y_pos, x_pos) in dot_positions:
                grid[row_idx, col_idx] = 1
    
    # If we have at least 8 rows and some columns, try decoding
    if grid.shape[0] >= 8:
        # Use first 8 rows and up to 15 columns
        decode_grid = grid[:8, :min(15, grid.shape[1])]
        
        print(f"Decoding grid of {decode_grid.shape[0]}x{decode_grid.shape[1]}")
        
        # Decode each column (skip row 0)
        for col in range(min(15, decode_grid.shape[1])):
            column_bits = decode_grid[1:, col]  # Skip first row
            value = sum(bit * (2 ** (6 - idx)) for idx, bit in enumerate(column_bits))
            
            desc = ""
            if col == 1:
                desc = f"Minutes: {value:02d}"
            elif col == 3:
                desc = f"Hour: {value:02d}"
            elif col == 4:
                desc = f"Day: {value:02d}"
            elif col == 5:
                desc = f"Month: {value:02d}"
            elif col == 6:
                desc = f"Year: 20{value:02d}"
            elif 9 <= col <= 12:
                desc = f"Serial digit"
            
            print(f"Col {col:2d}: {''.join(str(b) for b in column_bits)} = {value:3d}  {desc}")
