#!/usr/bin/env python3
"""
Gallery Creation Time Integration
Example function to add creation time metadata to plot items.
This should be integrated into your existing Python gallery generation code.
"""

from pathlib import Path


def add_creation_time_to_items(items, base_path):
    """
    Add creation time to plot items for sorting functionality.

    Args:
        items: List of plot item dictionaries
        base_path: Base path where plot files are located

    Returns:
        Updated items list with creation_time field
    """
    for item in items:
        try:
            # Try to get creation time from PNG file first, then PDF
            png_path = None
            pdf_path = None

            # Extract relative path from href
            if 'png_href' in item:
                png_rel_path = item['png_href'].replace('../', '').replace(
                    './', '')
                png_path = Path(base_path) / png_rel_path

            if 'pdf_href' in item:
                pdf_rel_path = item['pdf_href'].replace('../', '').replace(
                    './', '')
                pdf_path = Path(base_path) / pdf_rel_path

            # Use PNG creation time if available, otherwise PDF
            creation_time = 0
            if png_path and png_path.exists():
                creation_time = int(png_path.stat().st_ctime)
            elif pdf_path and pdf_path.exists():
                creation_time = int(pdf_path.stat().st_ctime)

            # Add creation time as timestamp (JavaScript can handle this)
            item['creation_time'] = creation_time

        except Exception as e:
            # Fallback to 0 if there's any error
            name = item.get('name', 'unknown')
            print(f"Warning: Could not get creation time for {name}: {e}")
            item['creation_time'] = 0

    return items


def example_integration():
    """
    Example of how to integrate this into your existing gallery generation.
    """
    # This would be part of your existing gallery generation code
    items = [
        {
            'name': 'plot1.png',
            'png_href': './plot1.png',
            'pdf_href': './plot1.pdf'
        },
        {
            'name': 'plot2.png',
            'png_href': './plot2.png',
            'pdf_href': './plot2.pdf'
        }
    ]

    base_path = "/path/to/your/gallery/directory"

    # Add creation times
    items_with_time = add_creation_time_to_items(items, base_path)

    # Now items_with_time can be passed to your Jinja2 template
    # The template will have access to item.creation_time for each item

    return items_with_time


if __name__ == "__main__":
    # Test the function
    items = example_integration()
    for item in items:
        created = item['creation_time']
        print(f"Plot: {item['name']}, Created: {created}")
