from multiplayer_crosswords.crossword_algorithm import generate_grid_template
import pytest

def test_generate_grid_template_min_length_4_strict():
    width = 15
    height = 15
    min_len = 4 # STRICTER
    
    def get_len_at(grid, r, c, dr, dc):
        # Scan backward
        curr_r, curr_c = r, c
        while curr_r >= 0 and curr_c >= 0 and grid[curr_r][curr_c] != '#':
            curr_r -= dr
            curr_c -= dc
        start_r, start_c = curr_r + dr, curr_c + dc
        
        # Scan forward
        curr_r, curr_c = r, c
        while curr_r < height and curr_c < width and grid[curr_r][curr_c] != '#':
            curr_r += dr
            curr_c += dc
        end_r, end_c = curr_r - dr, curr_c - dc
        
        if dr == 0: # Horizontal
            return end_c - start_c + 1
        else: # Vertical
            return end_r - start_r + 1

    # Run multiple times
    for seed in range(50):
        grid = generate_grid_template(width=width, height=height, block_ratio=0.25, seed=seed, min_slot_length=min_len)
        
        failed_cells = []
        for r in range(height):
            for c in range(width):
                if grid[r][c] == '':
                    h_len = get_len_at(grid, r, c, 0, 1)
                    v_len = get_len_at(grid, r, c, 1, 0)
                    
                    if h_len < min_len and v_len < min_len:
                        failed_cells.append((r, c, h_len, v_len))
        
        if failed_cells:
            print(f"Seed {seed} failed. Invalid cells found:")
            # Only print first few
            for cell in failed_cells[:5]:
                print(f"Cell ({cell[0]}, {cell[1]}) has h_len={cell[2]} and v_len={cell[3]}")
            
            # Print grid heavily
            print("\nFAILED GRID:")
            for r in range(height):
                row_str = ""
                for c in range(width):
                    if grid[r][c] == '#':
                        row_str += "# "
                    else:
                         # check if this cell is failed
                        is_failed = False
                        for fc in failed_cells:
                            if fc[0] == r and fc[1] == c:
                                is_failed = True
                                break
                        row_str += "X " if is_failed else ". "
                print(row_str)
                
        assert len(failed_cells) == 0, f"Found {len(failed_cells)} invalid cells for seed {seed}"
