#!/usr/bin/env python3
"""
Demo Snapshot Downloader

This script demonstrates the snapshot downloader functionality by
downloading a small set of snapshots and generating an HTML report.
"""

import asyncio
import logging
import sys
import os
from datetime import datetime, timedelta

# Add the current directory to the path so we can import modules
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from snapshot_downloader import SnapshotDownloader


async def demo_snapshot_download():
    """Demonstrate snapshot downloading functionality."""
    print("🎯 ParentZone Snapshot Downloader Demo")
    print("=" * 60)

    # Configuration
    email = "tudor.sitaru@gmail.com"
    password = "mTVq8uNUvY7R39EPGVAm@"
    output_dir = "demo_snapshots"

    # Setup logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )

    try:
        print("\n🔐 Step 1: Initialize Snapshot Downloader")
        print("-" * 40)

        downloader = SnapshotDownloader(
            output_dir=output_dir,
            email=email,
            password=password
        )

        print(f"✅ Downloader initialized")
        print(f"   Output directory: {output_dir}")
        print(f"   Authentication: Email/Password")

        print(f"\n📊 Step 2: Download Snapshots (Limited)")
        print("-" * 40)
        print("Downloading snapshots with limits for demo...")

        # Download snapshots with limits for demo
        html_file = await downloader.download_snapshots(
            type_ids=[15],  # Snapshot type
            date_from="2024-01-01",  # Start of 2024
            date_to="2024-03-31",    # First quarter only
            max_pages=3  # Limit to first 3 pages for demo
        )

        if html_file:
            print(f"\n✅ Demo completed successfully!")
            print(f"📄 HTML Report: {html_file}")

            # Print statistics
            print(f"\n📈 Demo Results:")
            print(f"   Total snapshots: {downloader.stats['total_snapshots']}")
            print(f"   Pages fetched: {downloader.stats['pages_fetched']}")
            print(f"   Failed requests: {downloader.stats['failed_requests']}")
            print(f"   Generated files: {downloader.stats['generated_files']}")

            print(f"\n🌐 How to View:")
            print(f"1. Open your file browser")
            print(f"2. Navigate to: {html_file}")
            print(f"3. Double-click the HTML file to open in browser")
            print(f"4. Use the search box to find specific snapshots")
            print(f"5. Click snapshot titles to expand/collapse details")

        else:
            print("⚠️ No snapshots found for the demo period")

        return True

    except Exception as e:
        print(f"❌ Demo failed with error: {e}")
        import traceback
        traceback.print_exc()
        return False


def show_demo_info():
    """Show information about the demo."""
    print("\n" + "=" * 60)
    print("📋 SNAPSHOT DOWNLOADER DEMO INFO")
    print("=" * 60)

    print("\n🎯 What This Demo Does:")
    print("• Authenticates with ParentZone API using login credentials")
    print("• Downloads snapshots (daily events) from Q1 2024")
    print("• Generates an interactive HTML report")
    print("• Shows pagination handling (limited to 3 pages)")
    print("• Demonstrates error handling and statistics")

    print("\n📄 HTML Report Features:")
    print("• Chronological listing of all snapshots")
    print("• Search functionality to find specific events")
    print("• Collapsible sections for detailed metadata")
    print("• Images and attachments (if available)")
    print("• Mobile-responsive design")
    print("• Raw JSON data for each snapshot (expandable)")

    print("\n⚙️ Technical Features Demonstrated:")
    print("• API authentication flow")
    print("• Pagination handling across multiple pages")
    print("• HTML escaping for security")
    print("• Date formatting and parsing")
    print("• Error handling and logging")
    print("• Statistics tracking")

    print("\n🔧 Configuration Options Available:")
    print("• Date range filtering")
    print("• Type ID filtering (default: 15 for snapshots)")
    print("• Page limits for testing")
    print("• Custom output directories")
    print("• API key or email/password authentication")


def main():
    """Main demo function."""
    show_demo_info()

    print("\n" + "=" * 60)
    print("🚀 STARTING DEMO")
    print("=" * 60)

    success = asyncio.run(demo_snapshot_download())

    if success:
        print("\n" + "=" * 60)
        print("🎉 DEMO COMPLETED SUCCESSFULLY!")
        print("=" * 60)
        print("✅ Snapshot downloader is working correctly")
        print("✅ HTML report generated with interactive features")
        print("✅ Pagination and authentication working")
        print("\n💡 Try the full downloader with:")
        print("   python3 snapshot_downloader.py --email your@email.com --password yourpass")
        print("   python3 config_snapshot_downloader.py --config snapshot_config.json")
    else:
        print("\n❌ Demo failed - check error messages above")
        return 1

    return 0


if __name__ == "__main__":
    exit(main())
