#!/usr/bin/env python3
"""
Facebook Auto-Poster for Genesis System (Mobile Emulation)
Handles automated posting to Business Pages via Playwright using iPhone emulation.
"""

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

# 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 run_posting_sequence():
    print("Initializing Facebook Auto-Poster (Mobile Mode)...")
    
    with sync_playwright() as p:
        # Launch browser
        browser = p.chromium.launch(headless=True)
        
        # Emulate iPhone 12
        iphone_12 = p.devices['iPhone 12']
        context = browser.new_context(
            **iphone_12,
            locale='en-AU',
            timezone_id='Australia/Sydney'
        )
        page = context.new_page()

        try:
            # 1. Login
            print("Logging in to mbasic...")
            page.goto("https://mbasic.facebook.com/")
            
            if page.is_visible("input[name='email']"):
                page.fill("input[name='email']", FB_USER)
                page.fill("input[name='pass']", FB_PASS)
                page.click("input[name='login']")
                page.wait_for_load_state("networkidle")
                
                # Check for 2FA/Checkpoint
                if "checkpoint" in page.url or "captcha" in page.content().lower():
                    print("CRITICAL: Facebook CAPTCHA/Checkpoint triggered.")
                    page.screenshot(path="/mnt/e/genesis-system/data/screenshots/fb_mobile_checkpoint.png")
                    print("Screenshot saved to fb_mobile_checkpoint.png.")
                    return

                # Check if login succeeded (look for home element or lack of login form)
                if page.is_visible("input[name='email']"):
                    print("Login failed (still on login page).")
                    page.screenshot(path="/mnt/e/genesis-system/data/screenshots/fb_login_fail.png")
                    return
                
                print("Login successful.")
            
            # 2. Get Business Pages
            print("Retrieving Pages...")
            page.goto("https://mbasic.facebook.com/pages/?category=your_pages")
            
            # Extract page links
            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:
                    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:
                    continue
                    
                post_text = parse_content(content_path)
                if not post_text:
                    continue

                print(f"Posting to {brand}...")
                page.goto(f"https://mbasic.facebook.com{page_links[brand]}")
                
                # Try to post
                try:
                    if page.is_visible("textarea[name='xc_message']"):
                        page.fill("textarea[name='xc_message']", post_text)
                        page.click("input[name='view_post']")
                        page.wait_for_load_state("networkidle")
                        page.click("input[name='action_publish']")
                        print(f"✅ Successfully posted to {brand}")
                    else:
                        print(f"Could not find post box for {brand}")
                        page.screenshot(path=f"/mnt/e/genesis-system/data/screenshots/debug_{brand}.png")
                except Exception as e:
                    print(f"❌ Failed to post to {brand}: {e}")
                
                time.sleep(5)

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

if __name__ == "__main__":
    run_posting_sequence()
