package main

import (
	"fmt"
	"log"
	"time"

	"git.teamworkapps.com/shortcut/cremote/client"
)

func main() {
	fmt.Println("=== Cremote Accessibility Tree Test ===")
	fmt.Println()

	// Create client
	c := client.NewClient("localhost", 8989)

	// Check if daemon is running
	fmt.Println("Checking daemon status...")
	running, err := c.CheckStatus()
	if err != nil || !running {
		log.Fatalf("Daemon is not running or not accessible: %v", err)
	}
	fmt.Println("✓ Daemon is running")

	// Open a new tab
	fmt.Println("Opening new tab...")
	tabID, err := c.OpenTab(5)
	if err != nil {
		log.Fatalf("Failed to open tab: %v", err)
	}
	fmt.Printf("✓ Opened tab: %s\n", tabID)

	// Navigate to a test page with accessibility content
	fmt.Println("Navigating to test page...")
	testURL := "https://brokedown.net/formtest.php"
	err = c.LoadURL(tabID, testURL, 10)
	if err != nil {
		log.Fatalf("Failed to load URL: %v", err)
	}
	fmt.Printf("✓ Loaded: %s\n", testURL)

	// Wait for page to fully load
	time.Sleep(2 * time.Second)

	// Test 1: Get full accessibility tree
	fmt.Println("\n--- Test 1: Full Accessibility Tree ---")
	fullTree, err := c.GetAccessibilityTree(tabID, nil, 10)
	if err != nil {
		log.Printf("❌ Failed to get full accessibility tree: %v", err)
	} else {
		fmt.Printf("✓ Retrieved full accessibility tree with %d nodes\n", len(fullTree.Nodes))

		// Print first few nodes for inspection
		fmt.Println("First 3 nodes:")
		for i, node := range fullTree.Nodes {
			if i >= 3 {
				break
			}
			fmt.Printf("  Node %d: ID=%s, Role=%s, Name=%s, Ignored=%v\n",
				i+1, node.NodeID, getRoleValue(node.Role), getNameValue(node.Name), node.Ignored)
		}
	}

	// Test 2: Get accessibility tree with limited depth
	fmt.Println("\n--- Test 2: Limited Depth Accessibility Tree ---")
	depth := 2
	limitedTree, err := c.GetAccessibilityTree(tabID, &depth, 10)
	if err != nil {
		log.Printf("❌ Failed to get limited depth accessibility tree: %v", err)
	} else {
		fmt.Printf("✓ Retrieved accessibility tree (depth=%d) with %d nodes\n", depth, len(limitedTree.Nodes))
	}

	// Test 3: Get partial accessibility tree for a specific element
	fmt.Println("\n--- Test 3: Partial Accessibility Tree ---")
	selector := "form"
	partialTree, err := c.GetPartialAccessibilityTree(tabID, selector, true, 10)
	if err != nil {
		log.Printf("❌ Failed to get partial accessibility tree: %v", err)
	} else {
		fmt.Printf("✓ Retrieved partial accessibility tree for '%s' with %d nodes\n", selector, len(partialTree.Nodes))

		// Print details of found nodes
		fmt.Println("Form-related accessibility nodes:")
		for i, node := range partialTree.Nodes {
			if i >= 5 { // Limit output
				break
			}
			fmt.Printf("  Node %d: Role=%s, Name=%s, BackendNodeID=%d\n",
				i+1, getRoleValue(node.Role), getNameValue(node.Name), node.BackendDOMNodeID)
		}
	}

	// Test 4: Query accessibility tree by role
	fmt.Println("\n--- Test 4: Query by Role ---")
	roleQuery, err := c.QueryAccessibilityTree(tabID, "", "", "textbox", 10)
	if err != nil {
		log.Printf("❌ Failed to query accessibility tree by role: %v", err)
	} else {
		fmt.Printf("✓ Found %d textbox elements\n", len(roleQuery.Nodes))

		for i, node := range roleQuery.Nodes {
			if i >= 3 { // Limit output
				break
			}
			fmt.Printf("  Textbox %d: Name=%s, Value=%s\n",
				i+1, getNameValue(node.Name), getValueValue(node.Value))
		}
	}

	// Test 5: Query accessibility tree by accessible name
	fmt.Println("\n--- Test 5: Query by Accessible Name ---")
	nameQuery, err := c.QueryAccessibilityTree(tabID, "", "Submit", "", 10)
	if err != nil {
		log.Printf("❌ Failed to query accessibility tree by name: %v", err)
	} else {
		fmt.Printf("✓ Found %d elements with accessible name 'Submit'\n", len(nameQuery.Nodes))

		for i, node := range nameQuery.Nodes {
			fmt.Printf("  Element %d: Role=%s, Name=%s\n",
				i+1, getRoleValue(node.Role), getNameValue(node.Name))
		}
	}

	// Test 6: Query with selector scope
	fmt.Println("\n--- Test 6: Query with Selector Scope ---")
	scopedQuery, err := c.QueryAccessibilityTree(tabID, "form", "", "button", 10)
	if err != nil {
		log.Printf("❌ Failed to query accessibility tree with selector scope: %v", err)
	} else {
		fmt.Printf("✓ Found %d button elements within form\n", len(scopedQuery.Nodes))
	}

	// Clean up
	fmt.Println("\n--- Cleanup ---")
	err = c.CloseTab(tabID, 5)
	if err != nil {
		log.Printf("❌ Failed to close tab: %v", err)
	} else {
		fmt.Println("✓ Tab closed")
	}

	fmt.Println("\n=== Accessibility Tree Test Completed ===")
}

// Helper functions to extract values from AXValue structs
func getRoleValue(axValue *client.AXValue) string {
	if axValue == nil || axValue.Value == nil {
		return "unknown"
	}
	if str, ok := axValue.Value.(string); ok {
		return str
	}
	return fmt.Sprintf("%v", axValue.Value)
}

func getNameValue(axValue *client.AXValue) string {
	if axValue == nil || axValue.Value == nil {
		return ""
	}
	if str, ok := axValue.Value.(string); ok {
		return str
	}
	return fmt.Sprintf("%v", axValue.Value)
}

func getValueValue(axValue *client.AXValue) string {
	if axValue == nil || axValue.Value == nil {
		return ""
	}
	if str, ok := axValue.Value.(string); ok {
		return str
	}
	return fmt.Sprintf("%v", axValue.Value)
}
