#!/usr/bin/env python3
"""
Demo script showing how to use the dead end marking functionality.
This script demonstrates various ways to mark and visualize dead ends in mazes.
"""

import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from maze_generation import MazeGenerator

def main():
    """Demonstrate dead end marking functionality."""
    print("Dead End Marking Demo")
    print("=" * 50)
    
    # Create a small maze for demonstration
    print("1. Creating a 15x15 maze...")
    generator = MazeGenerator(maze_size=15)
    
    # Show initial state
    print("\n2. Initial maze analysis:")
    analysis = generator.analyze_dead_ends()
    print(f"   Found {analysis['dead_end_count']} dead ends")
    print(f"   Dead end positions: {analysis['dead_end_positions'][:5]}...")  # Show first 5
    
    # Create output directory
    output_dir = "dead_end_demo_outputs"
    os.makedirs(output_dir, exist_ok=True)
    
    # Save initial maze
    initial_file = os.path.join(output_dir, "01_initial_maze.png")
    generator.save_maze_image(initial_file, show_grid=True, dpi=120)
    print(f"   Saved initial maze: {initial_file}")
    
    # Method 1: Mark all detected dead ends automatically
    print("\n3. Auto-marking all detected dead ends...")
    marked_count = generator.mark_all_detected_dead_ends()
    print(f"   Marked {marked_count} dead ends")
    
    # Save maze with all dead ends marked
    all_marked_file = os.path.join(output_dir, "02_all_dead_ends_marked.png")
    generator.save_maze_image(all_marked_file, show_grid=True, dpi=120, 
                             highlight_marked_dead_ends=True)
    print(f"   Saved maze with all dead ends marked: {all_marked_file}")
    
    # Method 2: Clear markings and mark specific dead ends
    print("\n4. Clearing all markings and demonstrating manual marking...")
    cleared_count = generator.clear_all_marked_dead_ends()
    print(f"   Cleared {cleared_count} markings")
    
    # Mark only the first 3 dead ends manually
    if analysis['dead_end_positions']:
        print("   Manually marking first 3 dead ends:")
        for i, (row, col) in enumerate(analysis['dead_end_positions'][:3]):
            success = generator.mark_dead_end(row, col)
            print(f"      Position ({row}, {col}): {'Success' if success else 'Failed'}")
    
    # Save maze with selective markings
    selective_file = os.path.join(output_dir, "03_selective_dead_ends.png")
    generator.save_maze_image(selective_file, show_grid=True, dpi=120, 
                             highlight_marked_dead_ends=True)
    print(f"   Saved maze with selective markings: {selective_file}")
    
    # Method 3: Demonstrate unmarking specific positions
    print("\n5. Demonstrating unmarking...")
    marked_positions = generator.get_marked_dead_ends()
    if marked_positions:
        pos_to_unmark = marked_positions[0]
        success = generator.unmark_dead_end(pos_to_unmark[0], pos_to_unmark[1])
        print(f"   Unmarked position {pos_to_unmark}: {'Success' if success else 'Failed'}")
        
        # Save maze after unmarking
        unmarked_file = os.path.join(output_dir, "04_after_unmarking.png")
        generator.save_maze_image(unmarked_file, show_grid=True, dpi=120, 
                                 highlight_marked_dead_ends=True)
        print(f"   Saved maze after unmarking: {unmarked_file}")
    
    # Method 4: Show comparison - with and without highlighting
    print("\n6. Creating comparison images...")
    
    # Mark all dead ends again for comparison
    generator.mark_all_detected_dead_ends()
    
    # Save with highlighting
    with_highlight_file = os.path.join(output_dir, "05_with_highlighting.png")
    generator.save_maze_image(with_highlight_file, show_grid=True, dpi=120, 
                             highlight_marked_dead_ends=True)
    
    # Save without highlighting (but dead ends are still marked in the data)
    without_highlight_file = os.path.join(output_dir, "06_without_highlighting.png")
    generator.save_maze_image(without_highlight_file, show_grid=True, dpi=120, 
                             highlight_marked_dead_ends=False)
    
    print(f"   Saved comparison images:")
    print(f"     With highlighting: {with_highlight_file}")
    print(f"     Without highlighting: {without_highlight_file}")
    
    # Final analysis
    print("\n7. Final analysis:")
    generator.print_dead_end_analysis(include_marked=True)
    
    print(f"\nDemo completed! Check the '{output_dir}' directory for output images.")
    print("\nKey features demonstrated:")
    print("  - Automatic dead end detection and marking")
    print("  - Manual marking and unmarking of specific positions")
    print("  - Visual highlighting with different colors and borders")
    print("  - Comparison views with/without highlighting")
    print("  - Detailed analysis including marked dead end statistics")

if __name__ == "__main__":
    main() 