#!/usr/bin/env python3
"""
Test browser reuse across multiple profile downloads
This verifies that Cloudflare challenge is only solved once
"""

import sys
import os
from pathlib import Path
from datetime import datetime

# Add modules directory to path
sys.path.insert(0, str(Path(__file__).parent))

from modules.imginn_module import ImgInnDownloader

def main():
    print("=" * 70)
    print("Browser Reuse Test - Multiple Profiles")
    print("=" * 70)
    print(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 70)
    print()
    print("This test will download from TWO different profiles sequentially")
    print("to verify the browser is reused and Cloudflare doesn't re-challenge.")
    print()

    # Create downloader with HEADLESS browser
    downloader = ImgInnDownloader(
        api_key="cf57fdb7577ada64d150431d6589c8f4",
        headless=True,
        show_progress=True,
        use_database=False
    )

    # Test profiles
    profiles = ["evalongoria", "kimkardashian"]

    try:
        for i, username in enumerate(profiles, 1):
            print("\n" + "=" * 70)
            print(f"PROFILE {i}/{len(profiles)}: @{username}")
            print("=" * 70)

            files = downloader.download_posts(
                username=username,
                days_back=14,
                max_posts=1
            )

            if files:
                print(f"✅ Downloaded {len(files)} file(s) from @{username}")
                for f in files:
                    print(f"  - {Path(f).name}")
            else:
                print(f"⚠️  No new files from @{username} (may have been downloaded already)")

        print("\n" + "=" * 70)
        print("TEST COMPLETE")
        print("=" * 70)
        print()
        print("✅ Browser reuse successful!")
        print("   - Check logs above: Cloudflare should only be solved ONCE")
        print("   - Second profile should say 'Browser already running, reusing...'")
        print()

    except KeyboardInterrupt:
        print("\n\n⚠️  Interrupted by user")
    except Exception as e:
        print(f"\n\n❌ Error: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # Explicitly stop browser when done with all profiles
        print("\nCleaning up browser...")
        downloader._stop_browser()
        print("✅ Browser closed")

if __name__ == "__main__":
    main()
