package main

import (
	"cursor-api-proxy/internal/providers/geminiweb"
	"fmt"
	"os"

	"github.com/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
	"github.com/go-rod/rod/lib/proto"
)

func main() {
	fmt.Println("Starting Gemini DOM detection...")
	fmt.Println("This will open a browser and analyze the Gemini web interface.")
	fmt.Println()

	// 啟動可見瀏覽器
	l := launcher.New().Headless(false)
	url, err := l.Launch()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to launch browser: %v\n", err)
		os.Exit(1)
	}

	browser := rod.New().ControlURL(url)
	if err := browser.Connect(); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to connect browser: %v\n", err)
		os.Exit(1)
	}
	defer browser.Close()

	page, err := browser.Page(proto.TargetCreateTarget{URL: "about:blank"})
	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to create page: %v\n", err)
		os.Exit(1)
	}

	// 載入 cookies（如果有）
	home, _ := os.UserHomeDir()
	cookieFile := home + "/.cursor-api-proxy/gemini-accounts/session-1/cookies.json"
	if _, err := os.Stat(cookieFile); err == nil {
		cookies, err := geminiweb.LoadCookiesFromFile(cookieFile)
		if err == nil {
			geminiweb.SetCookiesOnPage(page, cookies)
			fmt.Println("Loaded existing cookies")
		}
	}

	// 導航到 Gemini
	fmt.Println("Navigating to gemini.google.com...")
	if err := geminiweb.NavigateToGemini(page); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to navigate: %v\n", err)
	}

	fmt.Println()
	fmt.Println("Browser is now open. Please:")
	fmt.Println("1. Log in if needed")
	fmt.Println("2. Wait for the chat interface to fully load")
	fmt.Println("3. Look for the model selector dropdown")
	fmt.Println()
	fmt.Println("Press Enter to analyze the DOM...")
	fmt.Scanln()

	// 分析 DOM
	analyzeDOM(page)

	fmt.Println()
	fmt.Println("Press Enter to close...")
	fmt.Scanln()
}

func analyzeDOM(page *rod.Page) {
	fmt.Println("=== DOM Analysis ===")
	fmt.Println()

	// 尋找可能的輸入框
	fmt.Println("Looking for input fields...")
	selectors := []string{
		`textarea`,
		`[contenteditable="true"]`,
		`[role="textbox"]`,
		`input[type="text"]`,
	}
	for _, sel := range selectors {
		elements, err := page.Elements(sel)
		if err == nil && len(elements) > 0 {
			fmt.Printf("  Found %d elements with: %s\n", len(elements), sel)
			for i, el := range elements {
				tag, _ := el.Property("tagName")
				class, _ := el.Attribute("class")
				ariaLabel, _ := el.Attribute("aria-label")
				placeholder, _ := el.Attribute("placeholder")
				fmt.Printf("    [%d] tag=%s class=%s aria-label=%s placeholder=%s\n",
					i, tag, class, ariaLabel, placeholder)
			}
		}
	}

	// 尋找可能的發送按鈕
	fmt.Println()
	fmt.Println("Looking for send buttons...")
	buttonSelectors := []string{
		`button`,
		`[role="button"]`,
		`[type="submit"]`,
	}
	for _, sel := range buttonSelectors {
		elements, err := page.Elements(sel)
		if err == nil && len(elements) > 0 {
			fmt.Printf("  Found %d elements with: %s\n", len(elements), sel)
			for i, el := range elements {
				if i >= 5 {
					fmt.Printf("    ... and %d more\n", len(elements)-5)
					break
				}
				tag, _ := el.Property("tagName")
				class, _ := el.Attribute("class")
				ariaLabel, _ := el.Attribute("aria-label")
				text, _ := el.Text()
				text = truncate(text, 30)
				fmt.Printf("    [%d] tag=%s class=%s aria-label=%s text=%s\n",
					i, tag, class, ariaLabel, text)
			}
		}
	}

	// 尋找模型選擇器
	fmt.Println()
	fmt.Println("Looking for model selector...")
	modelSelectors := []string{
		`[aria-label*="model"]`,
		`[aria-label*="Model"]`,
		`button[aria-haspopup]`,
		`[data-test-id*="model"]`,
		`[class*="model"]`,
	}
	for _, sel := range modelSelectors {
		elements, err := page.Elements(sel)
		if err == nil && len(elements) > 0 {
			fmt.Printf("  Found with: %s\n", sel)
			for i, el := range elements {
				tag, _ := el.Property("tagName")
				class, _ := el.Attribute("class")
				ariaLabel, _ := el.Attribute("aria-label")
				text, _ := el.Text()
				fmt.Printf("    [%d] tag=%s class=%s aria-label=%s text=%s\n",
					i, tag, class, ariaLabel, truncate(text, 30))
			}
		}
	}
}

func truncate(s string, max int) string {
	if len(s) <= max {
		return s
	}
	return s[:max] + "..."
}
