import sys
import time
from playwright.sync_api import sync_playwright

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

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

    # Find comment containing Experience the full naval warfare
    comment = page.locator("div[role='article']:has-text('Experience the full naval warfare')").first
    if comment.count() == 0:
        comment = page.locator("div:has-text('Experience the full naval warfare')").last

    if comment.count() > 0:
        comment.scroll_into_view_if_needed()
        time.sleep(1)

        # Hover over comment to reveal 3 dots
        comment.hover()
        time.sleep(1)

        # Look for 3-dots button near comment
        action_btn = page.locator("div[aria-label='More options'], div[aria-label='Edit or delete this'], div[aria-label='Chỉnh sửa hoặc xóa bình luận này'], div[aria-label*='options'], div[aria-label*='tùy chọn']").last
        if not action_btn.is_visible():
            action_btn = comment.locator("..").locator("div[role='button']").last

        if action_btn.is_visible():
            action_btn.click(force=True)
            time.sleep(1.5)
            page.screenshot(path="FacebookAutoPoster/comment_menu.png")
            print("Menu opened, searching for Delete...")

            del_btn = page.locator("span:text-is('Delete'), div:text-is('Delete')").first
            if del_btn.is_visible():
                del_btn.click(force=True)
                time.sleep(1.5)
                # Confirm modal
                confirm_del = page.locator("div[role='dialog'] div[role='button']:has-text('Delete'), div[role='dialog'] div[aria-label='Delete']").last
                if confirm_del.is_visible():
                    confirm_del.click(force=True)
                    print("✅ Comment deleted successfully!")
                    time.sleep(2)

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