import asyncio
import sys
import json
from pathlib import Path
import re

# Add genesis-system to python path
sys.path.append(str(Path(__file__).resolve().parent.parent))

from genesis_v2.core.adk_orchestrator import adk_execute_browser_action
from tools.ask_user import ask_user

async def main():
    """
    Main async function to post on Facebook using GSB.
    """
    
    post_content_path = "/mnt/e/genesis-system/RECEPTIONISTAI/marketing/FACEBOOK_CONTENT_BATCH_1.md"
    
    # First, read the content of the file
    read_file_instruction = f"read_file {post_content_path}"
    result_json = await adk_execute_browser_action(read_file_instruction)
    post_content = ""
    try:
        result_data = json.loads(result_json)
        if result_data.get("action") == "read_file":
            raw_content = result_data.get("content", "")
            match = re.search(r"\*\*Caption\*\*:\n(.*?)\n\n", raw_content, re.DOTALL)
            if match:
                post_content = match.group(1).strip()
    except (json.JSONDecodeError, AttributeError):
        print(f"Could not parse content from file: {result_json}")
        return

    if not post_content:
        print("Could not extract post caption from file.")
        return

    instructions = [
        "navigate to https://mbasic.facebook.com",
        "fill in input[name='email'] with f.kloosterman@gmail.com",
        "fill in input[name='pass'] with Manouche6",
        "click the login button",
        "take a screenshot and save it to /mnt/e/genesis-system/data/screenshots/login_attempt.png",
        "check if the page contains the text 'Two-factor authentication required'",
    ]
    
    for instruction in instructions:
        result_json = await adk_execute_browser_action(instruction)
        
        try:
            result_data = json.loads(result_json)
            print(json.dumps(result_data, indent=2))
            if "check if" in instruction and result_data.get("engine") == "vision":
                if "yes" in result_data.get("action", {}).get("reasoning", "").lower():
                    # 2FA is required
                    response = await ask_user("Please provide the 2FA code from your authenticator app.")
                    fa2_code = response.text
                    
                    fa2_instructions = [
                        f"fill in input[name='approvals_code'] with {fa2_code}",
                        "click button[name='submit']"
                    ]

                    for fa2_instruction in fa2_instructions:
                        await adk_execute_browser_action(fa2_instruction)

        except json.JSONDecodeError:
            print(result_json)

    # The rest of the posting instructions would go here...

if __name__ == "__main__":
    asyncio.run(main())
