import sys
import time
from pathlib import Path

sys.path.append(str(Path("05_Production_Pipeline").resolve()))
from invisible_playwright import InvisiblePlaywright
from muse_invpw_driver import sync_worker_profile, DEFAULT_PROFILE

def test_upload():
    sync_worker_profile()
    test_img = Path("04_Assets/keyframes/ep01_scene01_shot01/start_frame_720p.png").resolve()
    print("Testing upload of:", test_img)
    if not test_img.exists():
        print("Image does not exist!")
        return

    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.goto("https://muse.ai/thread/new", wait_until="domcontentloaded", timeout=30000)
        time.sleep(3)
        
        file_input = page.locator('input[type="file"]').first
        print("File input count:", file_input.count())
        file_input.set_input_files(str(test_img))
        print("Set input files called. Waiting for preview/attachment...")
        
        for i in range(10):
            time.sleep(1)
            buttons = page.locator("button")
            for j in range(buttons.count()):
                b = buttons.nth(j)
                aria = b.get_attribute("aria-label") or ""
                title = b.get_attribute("title") or ""
                if any(w in f"{aria} {title}".lower() for w in ["gỡ", "xóa", "remove", "delete", "file", "đính kèm", "attachment"]):
                    print(f"[{i}s] Found attachment button: aria='{aria}', title='{title}'")
        
        screenshot_path = Path("04_Assets/test_upload_state.png").resolve()
        page.screenshot(path=str(screenshot_path))
        print("Saved screenshot to:", screenshot_path)

if __name__ == "__main__":
    test_upload()
