from playwright.sync_api import sync_playwright
import time

def run():
    with sync_playwright() as p:
        print("Launching browser...")
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        
        print("Navigating to login page...")
        page.goto("https://secure-suite-b60fbae0.base44.app/")
        time.sleep(3)
        
        print(f"Initial URL: {page.url}")
        
        # Login
        if page.query_selector("input[type='email']"):
            print("Found login form. Logging in...")
            page.fill("input[type='email']", "junsuwhy@gmail.com")
            page.fill("input[type='password']", "2!b*S5fWOVyu3v*")
            page.click("button[type='submit']")
            print("Clicked submit. Waiting...")
            page.wait_for_load_state('networkidle')
            time.sleep(5)
        else:
            print("No login form found. Maybe already logged in or different page?")
            
        print(f"Current URL: {page.url}")
        print(f"Page Title: {page.title()}")
        print("Visible text snippet:")
        print(page.inner_text("body")[:500])
        
        # Navigate to Asset Management
        print("Looking for Asset Management link...")
        found = False
        # Try to find any link or button with the text
        for text in ["Asset Management", "資產管理", "Assets", "資產"]:
            try:
                print(f"Trying to click text='{text}'")
                # Use a more generic selector
                page.click(f"text={text}", timeout=2000)
                found = True
                print(f"Clicked '{text}'")
                break
            except:
                pass
        
        if not found:
            print("Could not find Asset Management link.")
            # List all buttons and links text
            print("Available links/buttons:")
            for el in page.query_selector_all("a, button"):
                txt = el.inner_text()
                if txt.strip():
                    print(f" - {txt.strip()}")
            
            browser.close()
            return

        page.wait_for_load_state('networkidle')
        time.sleep(3)
        
        # Click Add Asset
        print("Looking for Add Asset button...")
        found_add = False
        for text in ["Add Asset", "新增資產", "Add", "新增"]:
            try:
                print(f"Trying to click text='{text}'")
                page.click(f"text={text}", timeout=2000)
                found_add = True
                print(f"Clicked '{text}'")
                break
            except:
                pass
                
        if not found_add:
            print("Could not find Add Asset button.")
            print("Available links/buttons:")
            for el in page.query_selector_all("a, button"):
                txt = el.inner_text()
                if txt.strip():
                    print(f" - {txt.strip()}")
            
            # Dump current page anyway, maybe it's the list page
            with open("asset_list_debug.html", "w") as f:
                f.write(page.content())
            browser.close()
            return
            
        print("Waiting for form to load...")
        time.sleep(3)
        
        # Capture
        print("Capturing form content...")
        html_content = page.content()
        with open("asset_form.html", "w") as f:
            f.write(html_content)
            
        page.screenshot(path="asset_form.png", full_page=True)
        print("Successfully captured asset_form.html and asset_form.png")
        browser.close()

if __name__ == "__main__":
    run()
