import sys
import time
from playwright.sync_api import sync_playwright

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

REEL_URL = "https://www.facebook.com/reel/4382288075237535/"

print("Connecting to browser on port 9224...")
with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp("http://127.0.0.1:9224")
    page = browser.contexts[0].pages[0]

    print(f"Navigating to {REEL_URL}...")
    page.goto(REEL_URL, wait_until="domcontentloaded", timeout=30000)
    time.sleep(3)

    page.screenshot(path="FacebookAutoPoster/reel_comments_check.png")
    print("Screenshot saved: reel_comments_check.png")

    # Click comment button to open comments sidebar
    comment_btn = page.locator("div[role='button']:has([aria-label*='Comment']), div[role='button']:has-text('2')").first
    print("Comment button found:", comment_btn.is_visible())
    if comment_btn.is_visible():
        comment_btn.click(force=True)
        time.sleep(2)
        page.screenshot(path="FacebookAutoPoster/reel_comments_opened.png")


    # Find the menu button on this comment
    # In Facebook comments, hover over the comment to reveal the three dots button
    comments = page.locator("div[role='article']").all()
    for c in comments:
        txt = c.inner_text()
        if "FKPhXdwFbII" in txt and "Episode 2" in txt:
            print("Found target comment to delete:", txt[:80])
            c.hover()
            time.sleep(1)
            # Find the 3-dots button inside or next to this comment
            dots = c.locator("div[role='button'][aria-label*='Action'], div[role='button'][aria-label*='More'], div[role='button'][aria-label*='Hành động'], div[role='button'][aria-haspopup='menu']").first
            if not dots.is_visible():
                # Try parent locator
                dots = page.locator("div[role='button'][aria-label*='Action'], div[role='button'][aria-label*='More'], div[role='button'][aria-label*='Hành động']").last
            
            print("Dots button visible:", dots.is_visible())
            if dots.is_visible():
                dots.click(force=True)
                time.sleep(1)
                page.screenshot(path="FacebookAutoPoster/comment_menu_open.png")
                # Click Delete
                delete_btn = page.locator("div[role='menuitem']:has-text('Delete'), div[role='menuitem']:has-text('Xóa'), span:has-text('Delete')").first
                print("Delete button visible:", delete_btn.is_visible())
                if delete_btn.is_visible():
                    delete_btn.click(force=True)
                    time.sleep(1)
                    # Confirm delete dialog
                    confirm_btn = page.locator("div[role='dialog'] div[role='button']:has-text('Delete'), div[role='dialog'] div[role='button']:has-text('Xóa')").first
                    if confirm_btn.is_visible():
                        confirm_btn.click(force=True)
                        print("Confirmed delete!")
                        time.sleep(2)
            break

    page.screenshot(path="FacebookAutoPoster/reel_after_cleanup.png")
    print("Saved reel_after_cleanup.png")
