package main

import (
	"cursor-api-proxy/internal/config"
	"cursor-api-proxy/internal/env"
	"cursor-api-proxy/internal/providers/geminiweb"
	"fmt"
	"os"
	"strings"
)

func main() {
	accountName := ""
	visible := false

	// 解析命令列參數
	for i := 1; i < len(os.Args); i++ {
		arg := os.Args[i]
		if arg == "--visible" || arg == "-v" {
			visible = true
		} else if arg == "--help" || arg == "-h" {
			printHelp()
			os.Exit(0)
		} else if !strings.HasPrefix(arg, "-") {
			accountName = arg
		}
	}

	e := env.OsEnvToMap()
	loaded := env.LoadEnvConfig(e, "")
	cfg := config.LoadBridgeConfig(e, "")

	cfg.GeminiAccountDir = loaded.GeminiAccountDir
	// 命令列參數優先於環境變數
	cfg.GeminiBrowserVisible = visible || loaded.GeminiBrowserVisible

	fmt.Printf("Session 儲存位置: %s\n", cfg.GeminiAccountDir)
	fmt.Printf("瀏覽器可見: %v\n", cfg.GeminiBrowserVisible)

	if err := geminiweb.RunLogin(cfg, accountName); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
}

func printHelp() {
	fmt.Println("使用方法: gemini-login [options] [session-name]")
	fmt.Println("")
	fmt.Println("選項:")
	fmt.Println("  --visible, -v    顯示瀏覽器視窗（預設隱藏）")
	fmt.Println("  --help, -h       顯示此說明")
	fmt.Println("")
	fmt.Println("環境變數:")
	fmt.Println("  GEMINI_ACCOUNT_DIR       Session 儲存目錄（預設: ~/.cursor-api-proxy/gemini-accounts）")
	fmt.Println("  GEMINI_BROWSER_VISIBLE   是否顯示瀏覽器（true/false，預設: false）")
	fmt.Println("")
	fmt.Println("範例:")
	fmt.Println("  gemini-login my-session")
	fmt.Println("  gemini-login --visible my-session")
	fmt.Println("  GEMINI_BROWSER_VISIBLE=true gemini-login")
}
