import os
import sys
import time
from pathlib import Path
from playwright.sync_api import sync_playwright

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

PROFILE_URL = "https://www.facebook.com/profile.php?id=61594841053758"
VIDEO_PATH = str(Path("content/shorts/ep2_short_2.mp4").resolve())
CAPTION = "💥 EUROPEAN ARTILLERY ON ASIAN RIVERS: The deadly Siamese naval assault (1785)"

print(f"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]

    # Close any open dialogs first
    page.keyboard.press("Escape")
    time.sleep(1)

    print("1. Opening profile...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded")
    time.sleep(4)

    # 2. Click Photo/video button directly on timeline
    pv_btn = page.locator("div[role='main'] div[role='button']:has-text('Photo/video'), div[role='button']:has-text('Ảnh/video')").first
    print("Timeline Photo/video button visible:", pv_btn.is_visible())

    cdp = page.context.new_cdp_session(page)

    if pv_btn.is_visible():
        print("Clicking Timeline Photo/video button...")
        pv_btn.click(force=True)
        time.sleep(2)

    create_dialog = page.locator("div[role='dialog']:has-text('Create post'), div[role='dialog']:has-text('Tạo bài viết')").first
    print("Create post dialog visible:", create_dialog.is_visible())

    # Find the video input
    doc = cdp.send("DOM.getDocument")
    root_node_id = doc["root"]["nodeId"]
    res = cdp.send("DOM.querySelectorAll", {
        "nodeId": root_node_id,
        "selector": "input[type='file'][accept*='video']"
    })
    node_ids = res.get("nodeIds", [])
    print(f"Found {len(node_ids)} video input nodeIds in DOM: {node_ids}")

    if node_ids:
        print(f"Setting file via CDP on nodeId {node_ids[0]}...")
        cdp.send("DOM.setFileInputFiles", {
            "files": [VIDEO_PATH],
            "nodeId": node_ids[0]
        })
        print("Waiting 6s...")
        time.sleep(6)

    # Type 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.insert_text(CAPTION)
        time.sleep(2)

    # Check Post button
    post_btn = create_dialog.locator("div[aria-label='Post'], div[role='button']:has-text('Post')").last
    print("Post button visible:", post_btn.is_visible())
    print("Post button text:", repr(post_btn.inner_text().strip()))
    print("Post button aria-disabled:", repr(post_btn.get_attribute("aria-disabled")))

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