import os
import asyncio
from playwright.async_api import async_playwright
# from urllib.parse import basename

async def download_pdf():
    # Set up download path
    download_path = './downloads/'
    
    # Create directory if it doesn't exist
    os.makedirs(download_path, exist_ok=True)
    
    # PDF URL
    bid_doc_link = 'https://bidplus.gem.gov.in/resources/upload_nas/MayQ225/bidding/biddoc/bid-7805326/1746429513.pdf'
    
    async with async_playwright() as p:
        # Launch browser
        browser = await p.chromium.launch(headless=True)
        
        # Create context with downloads enabled
        context = await browser.new_context(accept_downloads=True)
        
        # Open new page
        page = await context.new_page()
        
        # Add script to prevent context menu interference
        await page.add_init_script("""
            window.addEventListener('contextmenu', e => e.stopPropagation(), true);
        """)
        
        # Navigate to the PDF URL
        await page.goto(bid_doc_link)
        
        # Wait for download to start
        download = await page.wait_for_event('download')
        
        # Get filename from URL
        file_name = "downloaded_file.pdf"
        file_path = os.path.join(download_path, file_name)
        
        # Save the file
        await download.save_as(file_path)
        
        print(f"📄 Downloaded: {file_path}")
        
        # Close browser
        await browser.close()

# Run the async function
asyncio.run(download_pdf())