#!/usr/bin/env python3
"""
Direct DEDA library usage to manually try all pattern types
"""
import sys
import os

# Add deda-repo to path
sys.path.insert(0, 'deda-repo')

from libdeda.extract_yd import YDX
from libdeda import pattern_handler
import cv2

def try_all_decode_methods(image_path="Zard_uncompressed.png"):
    """Try every possible decoding method"""
    print(f"Attempting to decode {image_path}...")
    print()
    
    # Try different DPI values
    for dpi in [150, 300, 600, 1200, 1800, 2400]:
        print(f"\n{'='*70}")
        print(f"Testing with DPI: {dpi}")
        print(f"{'='*70}")
        
        try:
            # Extract dots
            yd = YDX(image_path, workAtDpi=dpi, inputDpi=dpi)
            
            # Get all matrices
            try:
                matrices = yd.getAllMatrices()
                print(f"Found {len(matrices)} matrices")
                
                if len(matrices) == 0:
                    print("No matrices extracted")
                    continue
                
                # Try each matrix with each pattern
                for mat_idx, matrix in enumerate(matrices[:3]):  # Try first 3
                    print(f"\n  Matrix {mat_idx}:")
                    print(f"  Shape: {matrix.shape if hasattr(matrix, 'shape') else 'unknown'}")
                    
                    # Get available pattern classes
                    pattern_classes = [
                        pattern_handler.Pattern2,
                        pattern_handler.Pattern3,
                        pattern_handler.Pattern4,
                        pattern_handler.Pattern5,
                        pattern_handler.Pattern1s2,
                        pattern_handler.Pattern1s3,
                    ]
                    
                    for pattern_class in pattern_classes:
                        try:
                            decoder = pattern_class(matrix)
                            result = decoder.decode()
                            
                            if result:
                                print(f"\n{'*'*70}")
                                print(f"SUCCESS WITH {pattern_class.__name__}!")
                                print(f"{'*'*70}")
                                print(f"DPI: {dpi}")
                                print(f"Matrix: {mat_idx}")
                                print(f"Result: {result}")
                                print(f"{'*'*70}\n")
                                return result, dpi, pattern_class.__name__
                        except Exception as e:
                            pass  # Silent fail
                
            except Exception as e:
                print(f"Error getting matrices: {e}")
                
        except Exception as e:
            print(f"Error with DPI {dpi}: {e}")
    
    print("\nNo successful decode found.")
    return None, None, None

if __name__ == "__main__":
    result, dpi, pattern = try_all_decode_methods()
    
    if result:
        print("\n" + "="*70)
        print("FINAL RESULT:")
        print("="*70)
        print(f"DPI: {dpi}")
        print(f"Pattern: {pattern}")
        print(f"Decoded data: {result}")
        print("="*70)
