#!/usr/bin/env python3
"""
Generate paginated HTML galleries for folders containing images.
Places HTML files in an 'html/' subfolder within each image directory.
"""

import os
from pathlib import Path
from collections import defaultdict

# Configuration
IMAGES_PER_PAGE = 100
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.tif', '.tiff'}
BASE_DIR = Path('/mnt/vision/data/kaust')

def get_image_files(folder):
    """Get all image files in a folder (non-recursive)."""
    images = []
    try:
        for item in sorted(os.listdir(folder)):
            if Path(item).suffix.lower() in IMAGE_EXTENSIONS:
                images.append(item)
    except (PermissionError, OSError):
        pass
    return images

def generate_page(folder, images, page_num, total_pages, html_dir, folder_name):
    """Generate a single HTML page for a gallery."""
    start_idx = (page_num - 1) * IMAGES_PER_PAGE
    end_idx = start_idx + IMAGES_PER_PAGE
    page_images = images[start_idx:end_idx]

    # Navigation
    prev_link = f'page{page_num-1}.html' if page_num > 1 else None
    next_link = f'page{page_num+1}.html' if page_num < total_pages else None
    index_link = '../../index.html'

    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{folder_name} - Page {page_num} of {total_pages}</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .header {{
            background: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        h1 {{
            margin: 0 0 10px 0;
            color: #333;
        }}
        .nav {{
            display: flex;
            gap: 10px;
            align-items: center;
            margin-top: 15px;
            flex-wrap: wrap;
        }}
        .nav a, .nav button {{
            padding: 8px 16px;
            background: #4a90e2;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }}
        .nav a:hover, .nav button:hover {{
            background: #357abd;
        }}
        .nav a.disabled {{
            background: #ccc;
            cursor: not-allowed;
            pointer-events: none;
        }}
        .nav a.folder-link {{
            background: #6c757d;
        }}
        .nav a.folder-link:hover {{
            background: #5a6268;
        }}
        .nav .page-info {{
            margin: 0 10px;
            font-weight: bold;
            color: #555;
        }}
        .gallery {{
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }}
        .gallery-item {{
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }}
        .gallery-item:hover {{
            transform: translateY(-4px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }}
        .gallery-item img {{
            width: 100%;
            height: 200px;
            object-fit: cover;
            display: block;
            cursor: pointer;
        }}
        .gallery-item .info {{
            padding: 8px;
        }}
        .gallery-item .filename {{
            font-size: 11px;
            color: #666;
            word-break: break-all;
            text-align: center;
            margin-bottom: 5px;
        }}
        .gallery-item .actions {{
            display: flex;
            gap: 5px;
            justify-content: center;
        }}
        .gallery-item .actions a {{
            font-size: 10px;
            padding: 4px 8px;
            background: #28a745;
            color: white;
            text-decoration: none;
            border-radius: 3px;
        }}
        .gallery-item .actions a:hover {{
            background: #218838;
        }}
        .controls {{
            background: white;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        .controls label {{
            margin-right: 10px;
            font-weight: bold;
        }}
        .controls input {{
            padding: 5px;
            width: 60px;
            margin-right: 10px;
        }}
        .lightbox {{
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.9);
            z-index: 1000;
        }}
        .lightbox img {{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            max-width: 90%;
            max-height: 90%;
            cursor: default;
        }}
        .lightbox .close {{
            position: absolute;
            top: 20px;
            right: 30px;
            color: white;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }}
        .lightbox .download {{
            position: absolute;
            top: 30px;
            left: 30px;
            padding: 10px 20px;
            background: #28a745;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-size: 16px;
        }}
        .lightbox .download:hover {{
            background: #218838;
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>{folder_name}</h1>
        <p>Gallery: {len(images)} total images | Page {page_num} of {total_pages} ({len(page_images)} images on this page)</p>
        <div class="nav">
            <a href="{index_link}">← Back to Index</a>
            <a href="../" class="folder-link">📁 Browse Folder</a>
            {'<a href="' + prev_link + '">← Previous</a>' if prev_link else '<a class="disabled">← Previous</a>'}
            <span class="page-info">Page {page_num} / {total_pages}</span>
            {'<a href="' + next_link + '">Next →</a>' if next_link else '<a class="disabled">Next →</a>'}
        </div>
    </div>

    <div class="controls">
        <label>Jump to page:</label>
        <input type="number" id="pageJump" min="1" max="{total_pages}" value="{page_num}">
        <button onclick="jumpToPage()">Go</button>
    </div>

    <div class="gallery">
"""

    for img in page_images:
        img_path = f'../{img}'
        html_content += f"""        <div class="gallery-item">
            <img src="{img_path}" alt="{img}" loading="lazy" onclick="showLightbox('{img_path}')">
            <div class="info">
                <div class="filename">{img}</div>
                <div class="actions">
                    <a href="{img_path}" download="{img}">Download</a>
                </div>
            </div>
        </div>
"""

    html_content += """    </div>

    <div class="header" style="margin-top: 20px;">
        <div class="nav">
"""
    html_content += f"""            <a href="{index_link}">← Back to Index</a>
            <a href="../" class="folder-link">📁 Browse Folder</a>
            {'<a href="' + prev_link + '">← Previous</a>' if prev_link else '<a class="disabled">← Previous</a>'}
            <span class="page-info">Page {page_num} / {total_pages}</span>
            {'<a href="' + next_link + '">Next →</a>' if next_link else '<a class="disabled">Next →</a>'}
        </div>
    </div>

    <div id="lightbox" class="lightbox" onclick="closeLightbox()">
        <span class="close">&times;</span>
        <a id="lightbox-download" class="download" href="" download="">Download</a>
        <img id="lightbox-img" src="" alt="" onclick="event.stopPropagation()">
    </div>

    <script>
        function jumpToPage() {{
            const page = document.getElementById('pageJump').value;
            if (page >= 1 && page <= {total_pages}) {{
                window.location.href = 'page' + page + '.html';
            }}
        }}

        function showLightbox(imgSrc) {{
            const img = document.getElementById('lightbox-img');
            const download = document.getElementById('lightbox-download');
            const filename = imgSrc.split('/').pop();

            img.src = imgSrc;
            download.href = imgSrc;
            download.download = filename;
            document.getElementById('lightbox').style.display = 'block';
        }}

        function closeLightbox() {{
            document.getElementById('lightbox').style.display = 'none';
        }}

        document.getElementById('pageJump').addEventListener('keypress', function(e) {{
            if (e.key === 'Enter') jumpToPage();
        }});

        // Keyboard navigation
        document.addEventListener('keydown', function(e) {{
            if (document.getElementById('lightbox').style.display === 'block') {{
                if (e.key === 'Escape') closeLightbox();
                return;
            }}
            {'if (e.key === "ArrowLeft") window.location.href = "' + prev_link + '";' if prev_link else ''}
            {'if (e.key === "ArrowRight") window.location.href = "' + next_link + '";' if next_link else ''}
        }});
    </script>
</body>
</html>
"""

    output_file = html_dir / f'page{page_num}.html'
    with open(output_file, 'w') as f:
        f.write(html_content)

    return output_file

def create_index_page(folder, total_pages, html_dir, folder_name, images_count):
    """Create an index page for the gallery."""
    html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{folder_name} - Gallery Index</title>
    <style>
        body {{
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .header {{
            background: white;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }}
        h1 {{
            margin: 0 0 10px 0;
            color: #333;
        }}
        .nav {{
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }}
        .nav a {{
            padding: 10px 20px;
            background: #4a90e2;
            color: white;
            text-decoration: none;
            border-radius: 4px;
        }}
        .nav a:hover {{
            background: #357abd;
        }}
        .nav a.folder-link {{
            background: #6c757d;
        }}
        .nav a.folder-link:hover {{
            background: #5a6268;
        }}
        .pages {{
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
            margin-top: 20px;
        }}
        .pages a {{
            padding: 15px;
            background: #4a90e2;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            text-align: center;
            font-weight: bold;
        }}
        .pages a:hover {{
            background: #357abd;
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>{folder_name} - Gallery</h1>
        <p>Total images: {images_count} | Pages: {total_pages} | Images per page: {IMAGES_PER_PAGE}</p>
        <div class="nav">
            <a href="../../index.html">← Back to Main Index</a>
            <a href="../" class="folder-link">📁 Browse Folder</a>
            <a href="page1.html">Start Gallery →</a>
        </div>
    </div>

    <div class="pages">
"""

    for i in range(1, total_pages + 1):
        start = (i - 1) * IMAGES_PER_PAGE + 1
        end = min(i * IMAGES_PER_PAGE, images_count)
        html_content += f'        <a href="page{i}.html">Page {i}<br><small>Images {start}-{end}</small></a>\n'

    html_content += """    </div>
</body>
</html>
"""

    output_file = html_dir / 'index.html'
    with open(output_file, 'w') as f:
        f.write(html_content)

    return output_file

def process_folder(folder_path):
    """Process a single folder and generate gallery pages."""
    folder = Path(folder_path)
    images = get_image_files(folder)

    if len(images) < 5:  # Skip folders with very few images
        return None

    # Create html subfolder
    html_dir = folder / 'html'
    html_dir.mkdir(exist_ok=True)

    # Calculate pagination
    total_pages = (len(images) + IMAGES_PER_PAGE - 1) // IMAGES_PER_PAGE

    folder_name = folder.name

    # Generate pages
    for page_num in range(1, total_pages + 1):
        generate_page(folder, images, page_num, total_pages, html_dir, folder_name)

    # Generate index
    create_index_page(folder, total_pages, html_dir, folder_name, len(images))

    return {
        'folder': folder_name,
        'images': len(images),
        'pages': total_pages
    }

def main():
    """Main function to process all folders."""
    print("Scanning for image folders...")

    results = []

    # Process all GSxxxxxx folders
    gs_folders = sorted([d for d in BASE_DIR.iterdir() if d.is_dir() and d.name.startswith('GS')])

    print(f"\nFound {len(gs_folders)} GSxxxxxx folders")
    print("Generating galleries...")

    for folder in gs_folders:
        print(f"Processing {folder.name}...", end=' ')
        result = process_folder(folder)
        if result:
            results.append(result)
            print(f"✓ {result['images']} images, {result['pages']} pages")
        else:
            print("✗ skipped (too few images)")

    # Process subdirectories in GSxxxxxx folders (fixed/, distances-m/)
    print("\nProcessing subdirectories...")
    for folder in gs_folders:
        for subfolder in ['fixed', 'distances-m']:
            subdir = folder / subfolder
            if subdir.exists() and subdir.is_dir():
                print(f"Processing {folder.name}/{subfolder}...", end=' ')
                result = process_folder(subdir)
                if result:
                    results.append(result)
                    print(f"✓ {result['images']} images, {result['pages']} pages")
                else:
                    print("✗ skipped")

    # Process other folders with images
    print("\nProcessing other folders...")
    for folder_name in ['panos', 'buildings']:
        folder_path = BASE_DIR / folder_name
        if folder_path.exists():
            # Process subfolders
            for subfolder in folder_path.iterdir():
                if subfolder.is_dir():
                    print(f"Processing {folder_name}/{subfolder.name}...", end=' ')
                    result = process_folder(subfolder)
                    if result:
                        results.append(result)
                        print(f"✓ {result['images']} images, {result['pages']} pages")
                    else:
                        print("✗ skipped")

    print(f"\n{'='*60}")
    print(f"Complete! Generated galleries for {len(results)} folders")
    print(f"Total images indexed: {sum(r['images'] for r in results)}")
    print(f"Total pages generated: {sum(r['pages'] for r in results)}")

if __name__ == '__main__':
    main()
