#!/usr/bin/env python3
"""
Nami Browser Integration Test
Tests the full pipeline: Agent → Nami Bridge → Browser Extension

Usage:
    python3 /opt/nami-army/test_browser.py
"""

import asyncio
import json
import sys
import time
from pathlib import Path

# Add agent to path
sys.path.insert(0, '/opt/nami-army')
from browser_agent import BrowserAgent

BRIDGE_URL = "ws://127.0.0.1:8888"


class Colors:
    GREEN = "\033[92m"
    RED = "\033[91m"
    YELLOW = "\033[93m"
    BLUE = "\033[94m"
    CYAN = "\033[96m"
    BOLD = "\033[1m"
    RESET = "\033[0m"


def ok(msg):
    print(f"  {Colors.GREEN}✅ {msg}{Colors.RESET}")


def fail(msg):
    print(f"  {Colors.RED}❌ {msg}{Colors.RESET}")


def warn(msg):
    print(f"  {Colors.YELLOW}⚠️  {msg}{Colors.RESET}")


def info(msg):
    print(f"  {Colors.CYAN}ℹ️  {msg}{Colors.RESET}")


async def main():
    print(f"\n{Colors.BOLD}🦞 Nami Browser Integration Test{Colors.RESET}")
    print(f"{'─' * 50}\n")
    
    agent = BrowserAgent(bridge_url=BRIDGE_URL, timeout=10)
    passed = 0
    failed = 0
    
    # ── Test 1: Agent Connection ────────────────────
    print(f"{Colors.BLUE}Test 1:{Colors.RESET} Agent connection to Nami Bridge")
    try:
        connected = await agent.connect()
        if connected:
            ok("Agent connected to bridge")
            passed += 1
        else:
            fail("Agent connection rejected")
            failed += 1
            return
    except Exception as e:
        fail(f"Agent connection failed: {e}")
        failed += 1
        return
    
    # ── Test 2: Ping / Browser Status ───────────────
    print(f"\n{Colors.BLUE}Test 2:{Colors.RESET} Browser status check")
    try:
        alive = await agent.ping()
        if alive:
            ok("Browser is connected and responding")
            passed += 1
        else:
            warn("Browser not connected — install Chrome Extension on your PC")
            info("Steps: chrome://extensions/ → Developer mode → Load unpacked → /root/nami_extension/")
            failed += 1
    except Exception as e:
        warn(f"Ping failed: {e}")
        failed += 1
    
    # ── Test 3: Page Info (if browser connected) ────
    if agent.browser_connected:
        print(f"\n{Colors.BLUE}Test 3:{Colors.RESET} Get page info")
        try:
            info_msg = await agent._send_and_wait(
                {"type": "get_page_info"},
                expected_type="page_info",
                timeout=10
            )
            if info_msg:
                ok(f"Page: {info_msg.get('title', '?')[:60]}")
                passed += 1
            else:
                warn("No page info returned")
                failed += 1
        except Exception as e:
            warn(f"Page info failed: {e}")
            failed += 1
    else:
        print(f"\n{Colors.BLUE}Test 3:{Colors.RESET} Get page info")
        warn("Skipped — browser not connected")
    
    # ── Summary ─────────────────────────────────────
    print(f"\n{'─' * 50}")
    total = passed + failed
    print(f"{Colors.BOLD}Results: {passed}/{total} passed{Colors.RESET}")
    
    if agent.browser_connected:
        print(f"\n{Colors.GREEN}🟢 System ready! Nami can control your browser.{Colors.RESET}")
        print(f"   Try: python3 /opt/nami-army/browser_agent.py --screenshot")
        print(f"   Try: python3 /opt/nami-army/browser_agent.py --eval 'document.title'")
    else:
        print(f"\n{Colors.YELLOW}🟡 Agent ready, but Browser not connected.{Colors.RESET}")
        print(f"   To connect: Install Nami Bridge Chrome Extension on your PC")
        print(f"   Files: /root/nami_extension/")
        print(f"   Bridge: {BRIDGE_URL} (accessible from your PC at ws://178.104.181.132:8888)")
    
    await agent.close()
    print()


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