import sys
import time
from playwright.sync_api import sync_playwright

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

CAPTION_FILE = "FacebookAutoPoster/post_content_ep2_short1.txt"
with open(CAPTION_FILE, "r", encoding="utf-8") as f:
    caption = f.read().strip()

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]

    # 1. Close the "Save this post as a draft?" dialog by clicking its close button X
    draft_close = page.locator("div[role='dialog']:has-text('Save this post as a draft') div[aria-label='Close'], div[role='dialog']:has-text('Lưu bài viết này làm bản nháp') div[aria-label='Đóng']").first
    if draft_close.is_visible():
        print("Closing draft prompt...")
        draft_close.click(force=True)
        time.sleep(1)

    # 2. Locate the Create post dialog
    create_dialog = page.locator("div[role='dialog']:has-text('Create post')").first
    print("Create post dialog visible:", create_dialog.is_visible())

    # 3. Focus textbox and insert caption
    textbox = create_dialog.locator("div[role='textbox'][contenteditable='true']").first
    print("Textbox visible:", textbox.is_visible())
    if textbox.is_visible():
        textbox.click(force=True)
        time.sleep(0.5)
        page.keyboard.press("Control+a")
        page.keyboard.press("Backspace")
        time.sleep(0.3)
        print("Typing caption...")
        page.keyboard.insert_text(caption)
        time.sleep(1)
        # Escape any hashtag dropdown
        page.keyboard.press("Escape")
        time.sleep(1)
        print("Caption typed successfully!")

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

    # 4. Check Post button
    post_btn = create_dialog.locator("div[role='button'][aria-label='Post'], div[role='button']:has-text('Post')").last
    print("Post button visible:", post_btn.is_visible())
    is_disabled = post_btn.get_attribute("aria-disabled")
    print(f"Post button aria-disabled: {is_disabled}")

    # 5. Click Post!
    if post_btn.is_visible() and is_disabled != "true":
        print("🚀🚀🚀 CLICKING POST BUTTON! 🚀🚀🚀")
        post_btn.click(force=True)
        time.sleep(5)
        page.screenshot(path="FacebookAutoPoster/post_clicked_state.png")
        print("Saved post_clicked_state.png")
    else:
        print("Post button is disabled or not visible.")
