#!/usr/bin/env python3
"""
Example: Using New eBay Research Parameters

This script demonstrates how to use the new minPrice, maxPrice, and topRatedProducts
parameters in the eBay research tool.
"""

import asyncio
from login import EbayLogin

async def demo_new_parameters():
    """Demonstrate the new price and top-rated parameters"""
    print("🔥 eBay Research - New Parameters Demo")
    print("="*50)

    # Initialize with debug mode for detailed output
    ebay_login = EbayLogin(debug=True, instance_id="demo")

    try:
        # Load credentials
        email, password = ebay_login.load_credentials()
        if not email or not password:
            print("❌ Failed to load credentials from config.info file")
            return

        # Start browser
        await ebay_login.start_browser(headless=True)

        # Check login status
        if await ebay_login.check_login_status():
            print("✅ Already logged in!")
        else:
            print("🔐 Logging in...")
            success = await ebay_login.login_to_ebay(email, password)
            if not success:
                print("❌ Login failed!")
                return

        print("\n" + "="*60)
        print("📊 DEMONSTRATION OF NEW PARAMETERS")
        print("="*60)

        # Example 1: Basic search without new parameters
        print("\n1️⃣ Basic Search (no price/rating filters)")
        print("-" * 40)
        basic_data = await ebay_login.fetch_multiple_offsets(
            keywords="wireless headphones",
            day_range=30,
            limit=25,
            offsets=[0, 50]
        )

        if basic_data:
            print(f"✅ Basic search: {basic_data.get('total_items', 0)} items found")

        # Example 2: Search with price range
        print("\n2️⃣ Search with Price Range ($20-$100)")
        print("-" * 40)
        price_filtered_data = await ebay_login.fetch_multiple_offsets(
            keywords="wireless headphones",
            day_range=30,
            limit=25,
            offsets=[0, 50],
            minPrice=20,
            maxPrice=100
        )

        if price_filtered_data:
            print(f"✅ Price filtered search: {price_filtered_data.get('total_items', 0)} items found")

        # Example 3: Search for only top-rated products
        print("\n3️⃣ Search for Top-Rated Products Only")
        print("-" * 40)
        top_rated_data = await ebay_login.fetch_multiple_offsets(
            keywords="wireless headphones",
            day_range=30,
            limit=25,
            offsets=[0, 50],
            topRatedProducts="SHOW"
        )

        if top_rated_data:
            print(f"✅ Top-rated search: {top_rated_data.get('total_items', 0)} items found")

        # Example 4: Search excluding top-rated products
        print("\n4️⃣ Search Excluding Top-Rated Products")
        print("-" * 40)
        non_top_rated_data = await ebay_login.fetch_multiple_offsets(
            keywords="wireless headphones",
            day_range=30,
            limit=25,
            offsets=[0, 50],
            topRatedProducts="EXCLUDE"
        )

        if non_top_rated_data:
            print(f"✅ Non-top-rated search: {non_top_rated_data.get('total_items', 0)} items found")

        # Example 5: Combined filters
        print("\n5️⃣ Combined Filters (Price + Top-Rated)")
        print("-" * 40)
        combined_data = await ebay_login.fetch_multiple_offsets(
            keywords="wireless headphones",
            day_range=30,
            limit=25,
            offsets=[0, 50],
            minPrice=50,
            maxPrice=200,
            topRatedProducts="SHOW"
        )

        if combined_data:
            print(f"✅ Combined filters search: {combined_data.get('total_items', 0)} items found")

        print("\n" + "="*60)
        print("📈 RESULTS SUMMARY")
        print("="*60)

        results = [
            ("Basic Search", basic_data),
            ("Price Range ($20-$100)", price_filtered_data),
            ("Top-Rated Only", top_rated_data),
            ("Exclude Top-Rated", non_top_rated_data),
            ("Combined Filters", combined_data)
        ]

        for name, data in results:
            items = data.get('total_items', 0) if data else 0
            print(f"{name:<25}: {items:>4} items")

        print("\n📁 All results saved to ./files/ directory")

    except Exception as e:
        print(f"❌ Error: {str(e)}")
    finally:
        await ebay_login.close_browser()

async def demo_parameter_combinations():
    """Show different parameter combinations"""
    print("\n🧪 Parameter Combination Examples")
    print("="*40)

    combinations = [
        {
            "name": "Budget Items",
            "params": {"minPrice": 1, "maxPrice": 25},
            "description": "Items under $25"
        },
        {
            "name": "Premium Items",
            "params": {"minPrice": 100, "maxPrice": 500},
            "description": "Items $100-$500"
        },
        {
            "name": "Top Rated Budget",
            "params": {"minPrice": 10, "maxPrice": 50, "topRatedProducts": "SHOW"},
            "description": "Top-rated items $10-$50"
        },
        {
            "name": "Non-Top Rated Premium",
            "params": {"minPrice": 200, "topRatedProducts": "EXCLUDE"},
            "description": "Non-top-rated items over $200"
        }
    ]

    for combo in combinations:
        print(f"\n🔸 {combo['name']}: {combo['description']}")
        print(f"   Parameters: {combo['params']}")

def main():
    """Run the demonstration"""
    print("🚀 Starting eBay Research New Parameters Demo...")
    asyncio.run(demo_new_parameters())
    asyncio.run(demo_parameter_combinations())

if __name__ == "__main__":
    main()
