#!/usr/bin/env python3
"""
Quick eBay Research Data Fetcher
Simple script to fetch data using your example URL
"""
import asyncio
import json
from login import EbayLogin


async def fetch_custom_url():
    """Fetch data from your specific eBay research URL"""

    # Your original URL parameters
    custom_url = (
        "https://www.ebay.com/sh/research/api/search?"
        "marketplace=EBAY-US&"
        "keywords=iphone+case&"
        "dayRange=90&"
        "endDate=1760790538450&"
        "startDate=1753014538450&"
        "categoryId=0&"
        "offset=100&"
        "limit=50&"
        "tabName=SOLD&"
        "tz=Africa%2FCairo&"
        "modules=searchResults"
    )

    ebay = EbayLogin()

    try:
        print("🚀 Starting eBay Research Data Fetch")
        print("=" * 50)

        # Start browser and check login
        await ebay.start_browser(headless=False)  # Set to True for headless

        if not await ebay.check_login_status():
            print("❌ Not logged in. Please run login.py first.")
            return

        print("✅ Logged in successfully!")
        print(f"🔗 Fetching: {custom_url}")

        # Navigate to your custom URL
        response = await ebay.page.goto(custom_url, wait_until='networkidle')
        await ebay.page.wait_for_timeout(3000)

        # Extract the JSON response
        try:
            page_text = await ebay.page.evaluate("document.body.textContent")

            # Clean HTML wrapper tags if present (using method from EbayLogin class)
            cleaned_text = ebay.clean_html_wrapper(page_text)

            print(f"🧹 Cleaned response length: {len(cleaned_text)} chars")

            data = json.loads(cleaned_text)
            if data.get('results') is None:
                print('{"no results found"}')
                return None

            ar = []
            for item in data['results']:
                print(item)
                tmp = {
                    "image": item['listing']['image']['URL'],
                    "itemId": item['listing']['itemId']['value'],
                    "title": item['listing']['title']['textSpans'][0]['text'],
                    "price": item['listing']['avgsalesprice']['textSpans'][0]['text'],
                    "itemsSold": (item['listing']['itemsSold']['textSpans'][0]['text']).replace(',', ''),
                    "totalsales": (item['listing']['totalsales']['textSpans'][0]['text']).replace(',', ''),
                    "datelastsold": item['listing']['datelastsold']['textSpans'][0]['text'],
                }
                ar.append(tmp)


            # Save the response
            import time
            timestamp = int(time.time())
            filename = f"ebay_custom_research_{timestamp}.json"
            filepath = f"{ebay.user_data_dir}/{filename}"

            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(ar, f, indent=2, ensure_ascii=False)

            print(f"✅ Data saved to: {filepath}")

            # Display summary
            if 'searchResults' in data and 'items' in data['searchResults']:
                items = data['searchResults']['items']
                print(f"📊 Found {len(items)} items")

                if items:
                    print("\n📋 Sample items:")
                    for i, item in enumerate(items[:3], 1):
                        title = item.get('title', 'No title')
                        price = item.get('price', {}).get('value', 'N/A')
                        sold_date = item.get('soldDate', 'N/A')
                        print(f"  {i}. {title[:50]}...")
                        print(f"     Price: ${price}, Sold: {sold_date}")

            return data

        except json.JSONDecodeError as e:
            print(f"❌ Could not parse JSON response: {str(e)}")
            # Save cleaned content or HTML fallback
            timestamp = int(time.time())

            # Try to save cleaned content first
            if cleaned_text and cleaned_text != page_text:
                filename = f"ebay_custom_research_{timestamp}_cleaned.txt"
                filepath = f"{ebay.user_data_dir}/{filename}"

                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(cleaned_text)

                print(f"📄 Cleaned response saved to: {filepath}")
            else:
                # Save as HTML instead
                content = await ebay.page.content()
                filename = f"ebay_custom_research_{timestamp}.html"
                filepath = f"{ebay.user_data_dir}/{filename}"

                with open(filepath, 'w', encoding='utf-8') as f:
                    f.write(content)

                print(f"📄 Response saved as HTML: {filepath}")
            return None

    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return None

    finally:
        await ebay.close_browser()


async def fetch_with_parameters():
    """Fetch data using the enhanced methods with parameters"""

    ebay = EbayLogin()

    try:
        print("\n🔬 Enhanced Research Data Fetch")
        print("=" * 50)

        # Start browser and check login
        await ebay.start_browser(headless=True)  # Headless for faster execution

        if not await ebay.check_login_status():
            print("❌ Not logged in. Please run login.py first.")
            return

        # Fetch data using the enhanced method
        data = await ebay.fetch_ebay_research_data(
            keywords="iphone case",
            day_range=90,
            offset=100,  # Same as your URL
            limit=50,    # Same as your URL
            category_id=0
        )

        if data:
            print("✅ Enhanced fetch completed successfully!")
        else:
            print("❌ Enhanced fetch failed.")

        return data

    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return None

    finally:
        await ebay.close_browser()


async def main():
    """Main function to run both methods"""

    print("🔍 eBay Research Data Fetcher")
    print("Choose method:")
    print("1. Direct URL fetch (your original URL)")
    print("2. Enhanced parameter-based fetch")
    print("3. Both methods")

    try:
        choice = input("\nEnter choice (1-3): ").strip()

        if choice == "1":
            await fetch_custom_url()
        elif choice == "2":
            await fetch_with_parameters()
        elif choice == "3":
            print("\n--- Method 1: Direct URL ---")
            await fetch_custom_url()

            print("\n--- Method 2: Enhanced Parameters ---")
            await fetch_with_parameters()
        else:
            print("Invalid choice. Running enhanced method by default...")
            await fetch_with_parameters()

    except KeyboardInterrupt:
        print("\n❌ Operation cancelled by user.")
    except Exception as e:
        print(f"❌ Error: {str(e)}")


if __name__ == "__main__":
    asyncio.run(main())
