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"
COVER_PATH = str(Path("FacebookAutoPoster/lifestyle_media/cover_california_coast.jpg").resolve())

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 {PROFILE_URL}...")
    page.goto(PROFILE_URL, wait_until="domcontentloaded", timeout=40000)
    time.sleep(3)
    page.keyboard.press("Escape")
    time.sleep(1)

    # Find Add Cover Photo button
    add_cover_btn = page.locator("div[role='button'][aria-label*='Cover photo'], div[role='button']:has-text('Add Cover Photo'), div[role='button']:has-text('Thêm ảnh bìa')").first
    print("Add Cover Photo button visible:", add_cover_btn.is_visible())

    if add_cover_btn.is_visible():
        add_cover_btn.click(force=True)
        time.sleep(1.5)
        page.screenshot(path="FacebookAutoPoster/cover_menu_open.png")
        print("Cover menu opened.")

        # Look for "Upload Photo" menu item
        upload_opt = page.locator("div[role='menuitem']:has-text('Upload photo'), div[role='menuitem']:has-text('Tải ảnh lên'), span:has-text('Upload photo')").first
        print("Upload photo option visible:", upload_opt.is_visible())

        if upload_opt.is_visible():
            with page.expect_file_chooser(timeout=8000) as fc_info:
                upload_opt.click(force=True)
            fc = fc_info.value
            fc.set_files(COVER_PATH)
            print("✅ File uploaded via file chooser! Waiting 8s for preview...")
            time.sleep(8)
            page.screenshot(path="FacebookAutoPoster/cover_preview.png")

            # Look for "Save changes" button
            save_btn = page.locator("div[role='button']:has-text('Save changes'), div[role='button']:has-text('Lưu thay đổi'), div[aria-label='Save changes']").first
            print("Save changes button visible:", save_btn.is_visible())
            if save_btn.is_visible():
                save_btn.click(force=True)
                print("Clicked Save changes! Waiting 5s...")
                time.sleep(5)

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