#!/usr/bin/env python3
"""
Advanced script to extract printer tracking dots using DEDA library
"""
import sys
from pathlib import Path
try:
    from libdeda import pattern_handler
    from libdeda.extract_yd import extractYD, YD_Patterns
    from libdeda.cmyk_to_rgb import rgb2cmyArray
    from libdeda.privacy import AnonmaskApplier
except ImportError as e:
    print(f"Error importing libdeda: {e}")
    print("Trying alternative approach...")

from PIL import Image
import numpy as np

def try_all_patterns(image_path, dpis=[300, 600, 700, 1200]):
    """Try to extract yellow dots with different DPI settings and patterns"""
    print(f"Analyzing {image_path}...")
    
    for dpi in dpis:
        print(f"\n=== Trying DPI: {dpi} ===")
        try:
            extractor = extractYD(image_path, dpi=dpi)
            
            # Try different pattern types
            for pattern_name in YD_Patterns:
                print(f"  Pattern: {pattern_name}")
                try:
                    extractor.setPattern(pattern_name)
                    matrix = extractor.getMatrix()
                    if matrix is not None and len(matrix) > 0:
                        print(f"    SUCCESS! Found dots with pattern {pattern_name}")
                        print(f"    Matrix shape: {np.array(matrix).shape}")
                        
                        # Try to decode
                        try:
                            decoder = pattern_handler.Pattern.create(pattern_name, matrix)
                            if decoder:
                                info = decoder.decode()
                                print(f"    Decoded info: {info}")
                                return info
                        except Exception as e:
                            print(f"    Could not decode: {e}")
                except Exception as e:
                    print(f"    Error with pattern {pattern_name}: {e}")
                    
        except Exception as e:
            print(f"  Error with DPI {dpi}: {e}")
    
    print("\nNo pattern successfully detected.")
    return None

def manual_yellow_extraction(image_path):
    """Manually extract yellow dots for inspection"""
    print(f"\n=== Manual yellow dot extraction ===")
    img = Image.open(image_path)
    img_array = np.array(img)
    
    if len(img_array.shape) == 3:
        # Convert to CMYK-like representation
        r = img_array[:,:,0].astype(float)
        g = img_array[:,:,1].astype(float)
        b = img_array[:,:,2].astype(float)
        
        # Yellow dots are typically low in blue channel
        # Look for areas where R and G are high but B is relatively low
        cyan = 255 - r
        magenta = 255 - g
        yellow = 255 - b
        
        # Yellow dots should have high yellow value
        yellow_normalized = (yellow - yellow.min()) / (yellow.max() - yellow.min())
        
        # Try different thresholds
        for percentile in [90, 95, 98, 99]:
            threshold = np.percentile(yellow, percentile)
            dots = yellow > threshold
            count = np.sum(dots)
            print(f"Percentile {percentile} (threshold={threshold:.2f}): {count} potential dots")
        
        # Save enhanced yellow channel
        yellow_enhanced = (yellow_normalized * 255).astype(np.uint8)
        Image.fromarray(yellow_enhanced).save('yellow_enhanced.png')
        print("Saved enhanced yellow channel to yellow_enhanced.png")
        
        # Try to find periodic pattern
        print(f"\nImage dimensions: {img_array.shape[:2]}")

if __name__ == "__main__":
    image_path = "Zard.jpg"
    
    # Try DEDA extraction
    result = try_all_patterns(image_path)
    
    # Also do manual extraction for inspection
    manual_yellow_extraction(image_path)
    
    if result:
        print(f"\n=== FINAL RESULT ===")
        print(result)
    else:
        print("\nCould not automatically decode. Manual analysis may be required.")
