#!/usr/bin/env python3
"""
Facebook Auto-Poster with Cookie Authentication
Bypasses login screen by injecting valid session cookies.
Usage: python3 scripts/facebook_poster_cookies.py --c_user "..." --xs "..."
"""

import os
import sys
import time
import random
import re
import argparse
from pathlib import Path
from playwright.sync_api import sync_playwright

# Content Path for Receptionist AI
CONTENT_PATH = "/mnt/e/genesis-system/RECEPTIONISTAI/marketing/FACEBOOK_CONTENT_BATCH_1.md"
TARGET_BRAND = "Receptionist AI"

def parse_content(file_path):
    """Extracts the first post from the markdown file."""
    try:
        content = Path(file_path).read_text()
        match = re.search(r"\*\*Caption\*\*:\n(.*?)\n\n", content, re.DOTALL)
        if match:
            return match.group(1).strip()
        return None
    except Exception as e:
        print(f"Error parsing {file_path}: {e}")
        return None

def run_with_cookies(c_user, xs):
    print(f"Initializing Facebook Auto-Poster for {TARGET_BRAND}...")
    
    post_text = parse_content(CONTENT_PATH)
    if not post_text:
        print("Error: Could not parse content.")
        return

    print(f"Content ready: {post_text[:50]}...")

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        # Use a generic mobile user agent to force mbasic
        context = browser.new_context(
            user_agent='Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36',
            viewport={'width': 375, 'height': 812}
        )
        
        # Inject cookies
        context.add_cookies([
            {'name': 'c_user', 'value': c_user, 'domain': '.facebook.com', 'path': '/'},
            {'name': 'xs', 'value': xs, 'domain': '.facebook.com', 'path': '/'}
        ])
        
        page = context.new_page()

        try:
            # 1. Verify Login by navigating to home
            print("Navigating to Facebook Home...")
            page.goto("https://mbasic.facebook.com/")
            
            if "login" in page.url or page.is_visible("input[name='email']"):
                print("❌ Cookie Login Failed: Redirected to login page.")
                page.screenshot(path="/mnt/e/genesis-system/data/screenshots/cookie_login_fail.png")
                return
            
            print("✅ Login Successful (Cookies Accepted)")

            # 2. Navigate Directly to Page
            # Using ID found in previous logs
            target_url = "https://mbasic.facebook.com/profile.php?id=61586913940075"
            print(f"Navigating directly to Page: {target_url}")
            page.goto(target_url)
            
            # Check for 'Switch' button or link (interstitial to switch profile)
            # Try text-based xpath selectors (most robust for React/modern FB)
            if page.is_visible("//div[text()='Switch']"):
                print("Clicking 'Switch' div...")
                page.click("//div[text()='Switch']")
                page.wait_for_load_state("networkidle")
            elif page.is_visible("//*[text()='Switch']"):
                 print("Clicking 'Switch' element (wildcard)...")
                 page.click("//*[text()='Switch']")
                 page.wait_for_load_state("networkidle")
            elif page.is_visible("//input[@value='Switch']"):
                 print("Clicking 'Switch' input...")
                 page.click("//input[@value='Switch']")
                 page.wait_for_load_state("networkidle")

            # Dismiss 'Not now' app prompt if present
            if page.is_visible("//*[text()='Not now']"):
                print("Dismissing app prompt...")
                page.click("//*[text()='Not now']")
                page.wait_for_load_state("networkidle")

            print("Posting...")
            
            # Strategy: Force navigate to mbasic home to ensure clean state
            print("Force navigating to mbasic home...")
            page.goto("https://mbasic.facebook.com/home.php")
            page.wait_for_load_state("networkidle")
            
            print("Attempting direct navigation to composer URL...")
            # Try specific mbasic composer URLs
            composer_urls = [
                "https://mbasic.facebook.com/composer/",
                "https://mbasic.facebook.com/composer/mbasic/",
                "https://m.facebook.com/composer/"
            ]
            
            for url in composer_urls:
                print(f"Navigating to {url}...")
                page.goto(url)
                page.wait_for_load_state("networkidle")
                if page.is_visible("textarea") or page.is_visible("input[type='file']"):
                    print("Composer found!")
                    break
            
            if page.is_visible("textarea[name='xc_message']") or page.is_visible("textarea") or page.is_visible("div[role='textbox']"):
                 # Handle generic textarea if specific name not found
                 if page.is_visible("textarea[name='xc_message']"):
                     page.fill("textarea[name='xc_message']", post_text)
                 elif page.is_visible("textarea"):
                     page.fill("textarea", post_text)
                 elif page.is_visible("div[role='textbox']"):
                     page.click("div[role='textbox']")
                     page.keyboard.type(post_text)
                     
                 # Look for Post/Publish button
                 # Vision says button text is 'POST' in all caps
                 print("Attempting to click POST button...")
                 post_btn_selectors = [
                     "div[aria-label='Post']",
                     "div[aria-label='POST']",
                     "//div[text()='POST']", 
                     "button:has-text('POST')",
                     "div[role='button']:has-text('POST')",
                     "input[name='view_post']"
                 ]
                 
                 posted = False
                 for selector in post_btn_selectors:
                     if page.is_visible(selector):
                         print(f"Clicking POST button: {selector}")
                         page.click(selector)
                         page.wait_for_load_state("networkidle")
                         time.sleep(3) # Wait for transition
                         if "composer" not in page.url and not page.is_visible("textarea"):
                             print("Successfully left composer page.")
                             posted = True
                             break
                 
                 if not posted:
                     print("Warning: Might still be on composer page. Trying force click on top-right POST link...")
                     # Try to find the top right POST link usually in header
                     page.evaluate("""() => {
                        const elements = document.querySelectorAll('div, span, a, button');
                        for (let el of elements) {
                            if (el.innerText === 'POST') {
                                el.click();
                                return;
                            }
                        }
                     }""")
                     time.sleep(5)

                 # Confirm publish if needed (mbasic usually has a preview step)
                 if page.is_visible("input[name='action_publish']"):
                     page.click("input[name='action_publish']")
                     
                 print(f"✅ SUCCESSFULLY POSTED to {TARGET_BRAND}")
                 page.screenshot(path="/mnt/e/genesis-system/data/screenshots/post_success.png")
            else:
                print("❌ Could not find post input box.")
                page.screenshot(path="/mnt/e/genesis-system/data/screenshots/post_debug.png")

        except Exception as e:
            print(f"Global Error: {e}")
            page.screenshot(path="/mnt/e/genesis-system/data/screenshots/cookie_error.png")
        finally:
            browser.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--c_user", required=True, help="c_user cookie value")
    parser.add_argument("--xs", required=True, help="xs cookie value")
    args = parser.parse_args()
    
    run_with_cookies(args.c_user, args.xs)
