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')

IMAGE_PATH = str(Path("FacebookAutoPoster/lifestyle_media/seven_coastal_highway1.jpg").resolve())

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

    # Inspect current modal
    dialog = page.locator("div[role='dialog']:has-text('Create post')").first
    print("Dialog is visible:", dialog.is_visible())

    # Check audience button
    aud_btn = dialog.locator("div[role='button'][aria-haspopup='listbox'], div[role='button']:has-text('Friends'), div[role='button']:has-text('Public')").first
    print("Audience button visible:", aud_btn.is_visible(), "Text:", aud_btn.inner_text() if aud_btn.is_visible() else "N/A")

    if aud_btn.is_visible() and "Public" not in aud_btn.inner_text():
        print("Switching audience to Public for maximum organic reach...")
        aud_btn.click(force=True)
        time.sleep(1.5)
        pub_opt = page.locator("div[role='radio']:has-text('Public'), div[role='button']:has-text('Public'), span:has-text('Public')").first
        if pub_opt.is_visible():
            pub_opt.click(force=True)
            time.sleep(1)
            # Check for Done button
            done_btn = page.locator("div[role='button']:has-text('Done'), div[aria-label='Done']").first
            if done_btn.is_visible():
                done_btn.click(force=True)
                time.sleep(1)
            print("✅ Audience set to Public!")

    # Check Photo/video button in modal
    photo_icon = dialog.locator("div[aria-label*='Photo/video'], div[role='button'][aria-label*='Photo/video']").first
    print("Photo icon visible:", photo_icon.is_visible())

    # Try file chooser with click
    if photo_icon.is_visible():
        with page.expect_file_chooser(timeout=5000) as fc_info:
            photo_icon.click(force=True)
        fc = fc_info.value
        print("Got FileChooser! Setting file:", IMAGE_PATH)
        fc.set_files(IMAGE_PATH)
        time.sleep(4)

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