#!/usr/bin/env python3
"""
Facebook Auto-Poster for Genesis System
Handles automated posting to Business Pages via Playwright.
STRICT PRIVACY MANDATE: NO interaction with personal profile. Direct navigation to Pages only.
"""

import os
import sys
import time
import random
import re
from pathlib import Path

# Add scripts dir to path to import browser_agent
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from browser_agent import BrowserAgent

# Credentials
FB_USER = "f.kloosterman@gmail.com"
FB_PASS = "Manouche6"

# Content Paths
CONTENT_MAP = {
    "Sunaiva": "/mnt/e/genesis-system/Sunaiva/marketing/FACEBOOK_CONTENT_BATCH_1.md",
    "AgileAdapt": "/mnt/e/genesis-system/AGILEADAPT/marketing/FACEBOOK_CONTENT_BATCH_1.md",
    "Receptionist AI": "/mnt/e/genesis-system/RECEPTIONISTAI/marketing/FACEBOOK_CONTENT_BATCH_1.md"
}

def parse_content(file_path):
    """Extracts the first post from the markdown file."""
    try:
        content = Path(file_path).read_text()
        # Simple regex to find the first Caption block
        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 human_type(page, selector, text):
    """Types text like a human (variable speed)."""
    for char in text:
        page.type(selector, char, delay=random.randint(50, 150))

def run_posting_sequence():
    print("Initializing Facebook Auto-Poster...")
    agent = BrowserAgent(headless=False) # Headless=False to handle potential checkpoints visually if needed (though running in CLI env, will rely on screenshots)
    # Actually, for CLI environment, we usually need headless. But if debugging 2FA... 
    # Sticking to headless=True for stability in this env, assuming BrowserAgent defaults.
    # Re-initializing with headless=True as per original script default.
    agent.headless = True 
    agent.start()
    agent.new_page()
    page = agent.page

    try:
        # 1. Login (Directly to login page, avoiding main feed)
        print("Logging in...")
        agent.navigate("https://mbasic.facebook.com/") # mbasic is easier for automation
        
        if page.is_visible("input[name='email']"):
            page.fill("input[name='email']", FB_USER)
            page.fill("input[name='pass']", FB_PASS)
            
            # Try multiple selectors for the login button
            if page.is_visible("input[name='login']"): # mbasic
                page.click("input[name='login']")
            elif page.is_visible("input[type='submit']"): # alternative mbasic
                page.click("input[type='submit']")
            elif page.is_visible("button[name='login']"): # desktop
                page.click("button[name='login']")
            elif page.is_visible("[data-testid='royal_login_button']"): # alternative desktop
                page.click("[data-testid='royal_login_button']")
            else:
                print("Could not find login button. Taking screenshot.")
                agent.screenshot("login_button_missing.png")
                return

            page.wait_for_load_state("networkidle")
            
            # Check for 2FA/Checkpoint
            if "checkpoint" in page.url or "two_step_verification" in page.content():
                print("CRITICAL: Facebook 2FA/Checkpoint triggered.")
                agent.screenshot("fb_checkpoint.png")
                print("Screenshot saved to fb_checkpoint.png. Please authorize manually.")
                return

            print("Login successful.")
        
        # 2. Get Business Pages
        print("Retrieving Pages...")
        agent.navigate("https://mbasic.facebook.com/pages/?category=your_pages")
        
        # Extract page links (Naive approach for mbasic)
        # We need to match brand names to the links found
        page_links = {}
        links = page.query_selector_all("a")
        for link in links:
            text = link.inner_text().lower()
            href = link.get_attribute("href")
            
            if "sunaiva" in text:
                page_links["Sunaiva"] = href
            elif "agile" in text: # AgileAdapt
                page_links["AgileAdapt"] = href
            elif "receptionist" in text:
                page_links["Receptionist AI"] = href

        print(f"Found Pages: {list(page_links.keys())}")

        # 3. Post Content
        for brand, content_path in CONTENT_MAP.items():
            if brand not in page_links:
                print(f"⚠️ Page for {brand} not found. Skipping.")
                continue
                
            post_text = parse_content(content_path)
            if not post_text:
                print(f"⚠️ No content found for {brand}. Skipping.")
                continue

            print(f"posting to {brand}...")
            agent.navigate(f"https://mbasic.facebook.com{page_links[brand]}")
            
            # mbasic posting flow
            # Usually there is a "Publish" or "Write Post" input
            try:
                # Look for the status input
                # Note: mbasic selectors change, this is a best-effort attempt
                if page.is_visible("textarea[name='xc_message']"):
                    page.fill("textarea[name='xc_message']", post_text)
                    page.click("input[name='view_post']") # Preview
                    page.wait_for_load_state("networkidle")
                    page.click("input[name='action_publish']") # Confirm
                    print(f"✅ Successfully posted to {brand}")
                else:
                    # Try alternate selector structure
                    print(f"Could not find simple post box for {brand}. Taking debug screenshot.")
                    agent.screenshot(f"debug_{brand}.png")
            except Exception as e:
                print(f"❌ Failed to post to {brand}: {e}")
                agent.screenshot(f"error_{brand}.png")
            
            time.sleep(5) # Safety pause

    except Exception as e:
        print(f"Global Error: {e}")
        agent.screenshot("global_error.png")
    finally:
        agent.stop()

if __name__ == "__main__":
    run_posting_sequence()
