"""
AGENT: Computer Use (Dec 2025 Stack)
=====================================
Headless Chrome automation for GHL & Instantly.ai audits.
"""

import asyncio
import sys
import os
from playwright.async_api import async_playwright
from datetime import datetime

# Genesis Imports
sys.path.append(r"E:\genesis-system")
from genesis_memory_cortex import MemoryCortex, MemoryTier

# Load credentials
CREDENTIALS_FILE = r"E:\genesis-system\Credentials\Genesis Credentials additions.txt"

def load_credentials():
    """Parse credentials from file"""
    creds = {}
    with open(CREDENTIALS_FILE, 'r') as f:
        lines = f.readlines()
        for i, line in enumerate(lines):
            if 'GHL' in line:
                creds['ghl_user'] = lines[i+1].split(':')[1].strip()
                creds['ghl_pass'] = lines[i+2].split(':')[1].strip()
            elif 'Extendly' in line:
                creds['extendly_user'] = lines[i+1].split(':')[1].strip()
                creds['extendly_pass'] = lines[i+2].split(':')[1].strip()
    return creds

async def audit_ghl(page, username, password):
    """Audit GoHighLevel SaaS Pro account"""
    print("\n[GHL AUDIT] Starting...")
    
    try:
        # Navigate to login
        await page.goto('https://app.gohighlevel.com/login')
        await page.wait_for_load_state('networkidle')
        
        # Fill credentials
        await page.fill('input[type="email"]', username)
        await page.fill('input[type="password"]', password)
        
        # Attempt login
        await page.click('button[type="submit"]')
        await page.wait_for_timeout(5000)
        
        # Check for 2FA or errors
        current_url = page.url
        if '2fa' in current_url or 'verify' in current_url:
            print("[GHL AUDIT] ⚠️ 2FA DETECTED - Human Interception Required")
            return {"status": "blocked", "reason": "2FA"}
        
        # Screenshot dashboard
        screenshot_path = f"E:\\genesis-system\\staging\\ghl_dashboard_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
        await page.screenshot(path=screenshot_path)
        print(f"[GHL AUDIT] ✅ Screenshot saved: {screenshot_path}")
        
        return {"status": "success", "screenshot": screenshot_path}
        
    except Exception as e:
        error_msg = f"[GHL AUDIT] ❌ Error: {e}"
        print(error_msg)
        return {"status": "error", "error": str(e)}

async def audit_instantly(page):
    """Audit Instantly.ai account"""
    print("\n[INSTANTLY AUDIT] Starting...")
    print("[INSTANTLY AUDIT] ⚠️ Credentials Missing - Human Interception Required")
    return {"status": "blocked", "reason": "No credentials found"}

async def main():
    creds = load_credentials()
    cortex = MemoryCortex()
    
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context()
        page = await context.new_page()
        
        # Run audits
        ghl_result = await audit_ghl(page, creds['ghl_user'], creds['ghl_pass'])
        instantly_result = await audit_instantly(page)
        
        await browser.close()
        
        # Persist to Memory Continuum
        cortex.remember(
            content=f"GHL Audit Status: {ghl_result['status']}. Instantly Status: {instantly_result['status']}.",
            source="agent_computer_use",
            domain="technical",
            metadata={"ghl": ghl_result, "instantly": instantly_result}
        )
        
        if ghl_result['status'] == "blocked":
            cortex.remember(
                content=f"CRITICAL BLOCKER: GHL Audit requires 2FA interception.",
                source="agent_computer_use",
                domain="error",
                force_tier=MemoryTier.WORKING
            )

        # Report
        print("\n" + "="*60)
        print("COMPUTER USE AGENT: AUDIT COMPLETE")
        print("="*60)
        print(f"GHL Status: {ghl_result['status']}")
        print(f"Instantly Status: {instantly_result['status']}")
        print("="*60)

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