File size: 4,854 Bytes
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#!/usr/bin/env python3
"""
Simple debug test for crossword generator index errors.
"""

import asyncio
import sys
import logging
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.services.crossword_generator_fixed import CrosswordGeneratorFixed

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

async def test_with_static_words():
    """Test generator with static word lists."""
    
    # Create generator without vector service
    generator = CrosswordGeneratorFixed(vector_service=None)
    
    # Create test words
    test_words = [
        {"word": "CAT", "clue": "Feline pet"},
        {"word": "DOG", "clue": "Man's best friend"}, 
        {"word": "BIRD", "clue": "Flying animal"},
        {"word": "FISH", "clue": "Aquatic animal"},
        {"word": "ELEPHANT", "clue": "Large mammal"},
        {"word": "TIGER", "clue": "Striped cat"},
        {"word": "HORSE", "clue": "Riding animal"},
        {"word": "BEAR", "clue": "Large carnivore"}
    ]
    
    print(f"🧪 Testing crossword generation with {len(test_words)} words...")
    
    try:
        # Test multiple times to catch intermittent errors
        for attempt in range(10):
            print(f"\n🔬 Attempt {attempt + 1}/10")
            
            # Shuffle words to create different scenarios
            import random
            random.shuffle(test_words)
            
            # Override the word selection to use our test words
            generator._select_words = lambda topics, difficulty, use_ai: test_words
            
            result = await generator.generate_puzzle(["animals"], "medium", use_ai=False)
            
            if result:
                grid_size = len(result['grid'])
                word_count = len(result['clues'])
                print(f"✅ Attempt {attempt + 1} succeeded: {grid_size}x{grid_size} grid, {word_count} words")
            else:
                print(f"⚠️ Attempt {attempt + 1} returned None")
                
    except IndexError as e:
        print(f"❌ INDEX ERROR caught on attempt {attempt + 1}: {e}")
        import traceback
        traceback.print_exc()
        return False
    except Exception as e:
        print(f"❌ Other error on attempt {attempt + 1}: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    print(f"\n✅ All 10 attempts completed successfully!")
    return True

async def test_grid_placement_directly():
    """Test grid placement functions directly with problematic data."""
    
    generator = CrosswordGeneratorFixed(vector_service=None)
    
    # Test data that might cause issues
    test_cases = [
        {
            "words": ["A", "I"],  # Very short words
            "description": "Very short words"
        },
        {
            "words": ["VERYLONGWORDTHATMIGHTCAUSEISSUES", "SHORT"],
            "description": "Very long word with short word"
        },
        {
            "words": ["ABCDEFGHIJKLMNOP", "QRSTUVWXYZ"],  # Long words
            "description": "Two long words"
        },
        {
            "words": ["TEST", "SETS", "NETS", "PETS"],  # Multiple similar words
            "description": "Similar words with same endings"
        }
    ]
    
    for i, test_case in enumerate(test_cases):
        print(f"\n🔬 Grid test {i+1}: {test_case['description']}")
        
        try:
            word_list = test_case["words"]
            word_objs = [{"word": w, "clue": f"Clue for {w}"} for w in word_list]
            
            result = generator._create_grid(word_objs)
            
            if result:
                grid_size = len(result['grid'])
                word_count = len(result['placed_words'])
                print(f"✅ Grid test {i+1} succeeded: {grid_size}x{grid_size} grid, {word_count} words")
            else:
                print(f"⚠️ Grid test {i+1} returned None")
                
        except IndexError as e:
            print(f"❌ INDEX ERROR in grid test {i+1}: {e}")
            import traceback
            traceback.print_exc()
            return False
        except Exception as e:
            print(f"❌ Other error in grid test {i+1}: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    return True

if __name__ == "__main__":
    print("🧪 Starting debug tests for crossword generator...")
    
    async def run_tests():
        success1 = await test_with_static_words()
        success2 = await test_grid_placement_directly()
        
        if success1 and success2:
            print("\n🎉 All debug tests passed! No index errors detected.")
        else:
            print("\n❌ Some debug tests failed.")
    
    asyncio.run(run_tests())