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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
// Package browser provides cross-platform functionality for opening URLs in the default web browser.
// It abstracts the underlying operating system commands and provides a simple interface.
package browser

import (
	"fmt"
	"os/exec"
	"runtime"
	"strings"
	"sync"

	pkgbrowser "github.com/pkg/browser"
	log "github.com/sirupsen/logrus"
)

// incognitoMode controls whether to open URLs in incognito/private mode.
// This is useful for OAuth flows where you want to use a different account.
var incognitoMode bool

// lastBrowserProcess stores the last opened browser process for cleanup
var lastBrowserProcess *exec.Cmd
var browserMutex sync.Mutex

// SetIncognitoMode enables or disables incognito/private browsing mode.
func SetIncognitoMode(enabled bool) {
	incognitoMode = enabled
}

// IsIncognitoMode returns whether incognito mode is enabled.
func IsIncognitoMode() bool {
	return incognitoMode
}

// CloseBrowser closes the last opened browser process.
func CloseBrowser() error {
	browserMutex.Lock()
	defer browserMutex.Unlock()

	if lastBrowserProcess == nil || lastBrowserProcess.Process == nil {
		return nil
	}
	
	err := lastBrowserProcess.Process.Kill()
	lastBrowserProcess = nil
	return err
}

// OpenURL opens the specified URL in the default web browser.
// It uses the pkg/browser library which provides robust cross-platform support
// for Windows, macOS, and Linux.
// If incognito mode is enabled, it will open in a private/incognito window.
//
// Parameters:
//   - url: The URL to open.
//
// Returns:
//   - An error if the URL cannot be opened, otherwise nil.
func OpenURL(url string) error {
	log.Debugf("Opening URL in browser: %s (incognito=%v)", url, incognitoMode)

	// If incognito mode is enabled, use platform-specific incognito commands
	if incognitoMode {
		log.Debug("Using incognito mode")
		return openURLIncognito(url)
	}

	// Use pkg/browser for cross-platform support
	err := pkgbrowser.OpenURL(url)
	if err == nil {
		log.Debug("Successfully opened URL using pkg/browser library")
		return nil
	}

	log.Debugf("pkg/browser failed: %v, trying platform-specific commands", err)

	// Fallback to platform-specific commands
	return openURLPlatformSpecific(url)
}

// openURLPlatformSpecific is a helper function that opens a URL using OS-specific commands.
// This serves as a fallback mechanism for OpenURL.
//
// Parameters:
//   - url: The URL to open.
//
// Returns:
//   - An error if the URL cannot be opened, otherwise nil.
func openURLPlatformSpecific(url string) error {
	var cmd *exec.Cmd

	switch runtime.GOOS {
	case "darwin": // macOS
		cmd = exec.Command("open", url)
	case "windows":
		cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
	case "linux":
		// Try common Linux browsers in order of preference
		browsers := []string{"xdg-open", "x-www-browser", "www-browser", "firefox", "chromium", "google-chrome"}
		for _, browser := range browsers {
			if _, err := exec.LookPath(browser); err == nil {
				cmd = exec.Command(browser, url)
				break
			}
		}
		if cmd == nil {
			return fmt.Errorf("no suitable browser found on Linux system")
		}
	default:
		return fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
	}

	log.Debugf("Running command: %s %v", cmd.Path, cmd.Args[1:])
	err := cmd.Start()
	if err != nil {
		return fmt.Errorf("failed to start browser command: %w", err)
	}

	log.Debug("Successfully opened URL using platform-specific command")
	return nil
}

// openURLIncognito opens a URL in incognito/private browsing mode.
// It first tries to detect the default browser and use its incognito flag.
// Falls back to a chain of known browsers if detection fails.
//
// Parameters:
//   - url: The URL to open.
//
// Returns:
//   - An error if the URL cannot be opened, otherwise nil.
func openURLIncognito(url string) error {
	// First, try to detect and use the default browser
	if cmd := tryDefaultBrowserIncognito(url); cmd != nil {
		log.Debugf("Using detected default browser: %s %v", cmd.Path, cmd.Args[1:])
		if err := cmd.Start(); err == nil {
			storeBrowserProcess(cmd)
			log.Debug("Successfully opened URL in default browser's incognito mode")
			return nil
		}
		log.Debugf("Failed to start default browser, trying fallback chain")
	}

	// Fallback to known browser chain
	cmd := tryFallbackBrowsersIncognito(url)
	if cmd == nil {
		log.Warn("No browser with incognito support found, falling back to normal mode")
		return openURLPlatformSpecific(url)
	}

	log.Debugf("Running incognito command: %s %v", cmd.Path, cmd.Args[1:])
	err := cmd.Start()
	if err != nil {
		log.Warnf("Failed to open incognito browser: %v, falling back to normal mode", err)
		return openURLPlatformSpecific(url)
	}

	storeBrowserProcess(cmd)
	log.Debug("Successfully opened URL in incognito/private mode")
	return nil
}

// storeBrowserProcess safely stores the browser process for later cleanup.
func storeBrowserProcess(cmd *exec.Cmd) {
	browserMutex.Lock()
	lastBrowserProcess = cmd
	browserMutex.Unlock()
}

// tryDefaultBrowserIncognito attempts to detect the default browser and return
// an exec.Cmd configured with the appropriate incognito flag.
func tryDefaultBrowserIncognito(url string) *exec.Cmd {
	switch runtime.GOOS {
	case "darwin":
		return tryDefaultBrowserMacOS(url)
	case "windows":
		return tryDefaultBrowserWindows(url)
	case "linux":
		return tryDefaultBrowserLinux(url)
	}
	return nil
}

// tryDefaultBrowserMacOS detects the default browser on macOS.
func tryDefaultBrowserMacOS(url string) *exec.Cmd {
	// Try to get default browser from Launch Services
	out, err := exec.Command("defaults", "read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers").Output()
	if err != nil {
		return nil
	}

	output := string(out)
	var browserName string

	// Parse the output to find the http/https handler
	if containsBrowserID(output, "com.google.chrome") {
		browserName = "chrome"
	} else if containsBrowserID(output, "org.mozilla.firefox") {
		browserName = "firefox"
	} else if containsBrowserID(output, "com.apple.safari") {
		browserName = "safari"
	} else if containsBrowserID(output, "com.brave.browser") {
		browserName = "brave"
	} else if containsBrowserID(output, "com.microsoft.edgemac") {
		browserName = "edge"
	}

	return createMacOSIncognitoCmd(browserName, url)
}

// containsBrowserID checks if the LaunchServices output contains a browser ID.
func containsBrowserID(output, bundleID string) bool {
	return strings.Contains(output, bundleID)
}

// createMacOSIncognitoCmd creates the appropriate incognito command for macOS browsers.
func createMacOSIncognitoCmd(browserName, url string) *exec.Cmd {
	switch browserName {
	case "chrome":
		// Try direct path first
		chromePath := "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
		if _, err := exec.LookPath(chromePath); err == nil {
			return exec.Command(chromePath, "--incognito", url)
		}
		return exec.Command("open", "-na", "Google Chrome", "--args", "--incognito", url)
	case "firefox":
		return exec.Command("open", "-na", "Firefox", "--args", "--private-window", url)
	case "safari":
		// Safari doesn't have CLI incognito, try AppleScript
		return tryAppleScriptSafariPrivate(url)
	case "brave":
		return exec.Command("open", "-na", "Brave Browser", "--args", "--incognito", url)
	case "edge":
		return exec.Command("open", "-na", "Microsoft Edge", "--args", "--inprivate", url)
	}
	return nil
}

// tryAppleScriptSafariPrivate attempts to open Safari in private browsing mode using AppleScript.
func tryAppleScriptSafariPrivate(url string) *exec.Cmd {
	// AppleScript to open a new private window in Safari
	script := fmt.Sprintf(`
		tell application "Safari"
			activate
			tell application "System Events"
				keystroke "n" using {command down, shift down}
				delay 0.5
			end tell
			set URL of document 1 to "%s"
		end tell
	`, url)

	cmd := exec.Command("osascript", "-e", script)
	// Test if this approach works by checking if Safari is available
	if _, err := exec.LookPath("/Applications/Safari.app/Contents/MacOS/Safari"); err != nil {
		log.Debug("Safari not found, AppleScript private window not available")
		return nil
	}
	log.Debug("Attempting Safari private window via AppleScript")
	return cmd
}

// tryDefaultBrowserWindows detects the default browser on Windows via registry.
func tryDefaultBrowserWindows(url string) *exec.Cmd {
	// Query registry for default browser
	out, err := exec.Command("reg", "query",
		`HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice`,
		"/v", "ProgId").Output()
	if err != nil {
		return nil
	}

	output := string(out)
	var browserName string

	// Map ProgId to browser name
	if strings.Contains(output, "ChromeHTML") {
		browserName = "chrome"
	} else if strings.Contains(output, "FirefoxURL") {
		browserName = "firefox"
	} else if strings.Contains(output, "MSEdgeHTM") {
		browserName = "edge"
	} else if strings.Contains(output, "BraveHTML") {
		browserName = "brave"
	}

	return createWindowsIncognitoCmd(browserName, url)
}

// createWindowsIncognitoCmd creates the appropriate incognito command for Windows browsers.
func createWindowsIncognitoCmd(browserName, url string) *exec.Cmd {
	switch browserName {
	case "chrome":
		paths := []string{
			"chrome",
			`C:\Program Files\Google\Chrome\Application\chrome.exe`,
			`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
		}
		for _, p := range paths {
			if _, err := exec.LookPath(p); err == nil {
				return exec.Command(p, "--incognito", url)
			}
		}
	case "firefox":
		if path, err := exec.LookPath("firefox"); err == nil {
			return exec.Command(path, "--private-window", url)
		}
	case "edge":
		paths := []string{
			"msedge",
			`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
			`C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
		}
		for _, p := range paths {
			if _, err := exec.LookPath(p); err == nil {
				return exec.Command(p, "--inprivate", url)
			}
		}
	case "brave":
		paths := []string{
			`C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe`,
			`C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\brave.exe`,
		}
		for _, p := range paths {
			if _, err := exec.LookPath(p); err == nil {
				return exec.Command(p, "--incognito", url)
			}
		}
	}
	return nil
}

// tryDefaultBrowserLinux detects the default browser on Linux using xdg-settings.
func tryDefaultBrowserLinux(url string) *exec.Cmd {
	out, err := exec.Command("xdg-settings", "get", "default-web-browser").Output()
	if err != nil {
		return nil
	}

	desktop := string(out)
	var browserName string

	// Map .desktop file to browser name
	if strings.Contains(desktop, "google-chrome") || strings.Contains(desktop, "chrome") {
		browserName = "chrome"
	} else if strings.Contains(desktop, "firefox") {
		browserName = "firefox"
	} else if strings.Contains(desktop, "chromium") {
		browserName = "chromium"
	} else if strings.Contains(desktop, "brave") {
		browserName = "brave"
	} else if strings.Contains(desktop, "microsoft-edge") || strings.Contains(desktop, "msedge") {
		browserName = "edge"
	}

	return createLinuxIncognitoCmd(browserName, url)
}

// createLinuxIncognitoCmd creates the appropriate incognito command for Linux browsers.
func createLinuxIncognitoCmd(browserName, url string) *exec.Cmd {
	switch browserName {
	case "chrome":
		paths := []string{"google-chrome", "google-chrome-stable"}
		for _, p := range paths {
			if path, err := exec.LookPath(p); err == nil {
				return exec.Command(path, "--incognito", url)
			}
		}
	case "firefox":
		paths := []string{"firefox", "firefox-esr"}
		for _, p := range paths {
			if path, err := exec.LookPath(p); err == nil {
				return exec.Command(path, "--private-window", url)
			}
		}
	case "chromium":
		paths := []string{"chromium", "chromium-browser"}
		for _, p := range paths {
			if path, err := exec.LookPath(p); err == nil {
				return exec.Command(path, "--incognito", url)
			}
		}
	case "brave":
		if path, err := exec.LookPath("brave-browser"); err == nil {
			return exec.Command(path, "--incognito", url)
		}
	case "edge":
		if path, err := exec.LookPath("microsoft-edge"); err == nil {
			return exec.Command(path, "--inprivate", url)
		}
	}
	return nil
}

// tryFallbackBrowsersIncognito tries a chain of known browsers as fallback.
func tryFallbackBrowsersIncognito(url string) *exec.Cmd {
	switch runtime.GOOS {
	case "darwin":
		return tryFallbackBrowsersMacOS(url)
	case "windows":
		return tryFallbackBrowsersWindows(url)
	case "linux":
		return tryFallbackBrowsersLinuxChain(url)
	}
	return nil
}

// tryFallbackBrowsersMacOS tries known browsers on macOS.
func tryFallbackBrowsersMacOS(url string) *exec.Cmd {
	// Try Chrome
	chromePath := "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
	if _, err := exec.LookPath(chromePath); err == nil {
		return exec.Command(chromePath, "--incognito", url)
	}
	// Try Firefox
	if _, err := exec.LookPath("/Applications/Firefox.app/Contents/MacOS/firefox"); err == nil {
		return exec.Command("open", "-na", "Firefox", "--args", "--private-window", url)
	}
	// Try Brave
	if _, err := exec.LookPath("/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"); err == nil {
		return exec.Command("open", "-na", "Brave Browser", "--args", "--incognito", url)
	}
	// Try Edge
	if _, err := exec.LookPath("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"); err == nil {
		return exec.Command("open", "-na", "Microsoft Edge", "--args", "--inprivate", url)
	}
	// Last resort: try Safari with AppleScript
	if cmd := tryAppleScriptSafariPrivate(url); cmd != nil {
		log.Info("Using Safari with AppleScript for private browsing (may require accessibility permissions)")
		return cmd
	}
	return nil
}

// tryFallbackBrowsersWindows tries known browsers on Windows.
func tryFallbackBrowsersWindows(url string) *exec.Cmd {
	// Chrome
	chromePaths := []string{
		"chrome",
		`C:\Program Files\Google\Chrome\Application\chrome.exe`,
		`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
	}
	for _, p := range chromePaths {
		if _, err := exec.LookPath(p); err == nil {
			return exec.Command(p, "--incognito", url)
		}
	}
	// Firefox
	if path, err := exec.LookPath("firefox"); err == nil {
		return exec.Command(path, "--private-window", url)
	}
	// Edge (usually available on Windows 10+)
	edgePaths := []string{
		"msedge",
		`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
		`C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
	}
	for _, p := range edgePaths {
		if _, err := exec.LookPath(p); err == nil {
			return exec.Command(p, "--inprivate", url)
		}
	}
	return nil
}

// tryFallbackBrowsersLinuxChain tries known browsers on Linux.
func tryFallbackBrowsersLinuxChain(url string) *exec.Cmd {
	type browserConfig struct {
		name string
		flag string
	}
	browsers := []browserConfig{
		{"google-chrome", "--incognito"},
		{"google-chrome-stable", "--incognito"},
		{"chromium", "--incognito"},
		{"chromium-browser", "--incognito"},
		{"firefox", "--private-window"},
		{"firefox-esr", "--private-window"},
		{"brave-browser", "--incognito"},
		{"microsoft-edge", "--inprivate"},
	}
	for _, b := range browsers {
		if path, err := exec.LookPath(b.name); err == nil {
			return exec.Command(path, b.flag, url)
		}
	}
	return nil
}

// IsAvailable checks if the system has a command available to open a web browser.
// It verifies the presence of necessary commands for the current operating system.
//
// Returns:
//   - true if a browser can be opened, false otherwise.
func IsAvailable() bool {
	// Check platform-specific commands
	switch runtime.GOOS {
	case "darwin":
		_, err := exec.LookPath("open")
		return err == nil
	case "windows":
		_, err := exec.LookPath("rundll32")
		return err == nil
	case "linux":
		browsers := []string{"xdg-open", "x-www-browser", "www-browser", "firefox", "chromium", "google-chrome"}
		for _, browser := range browsers {
			if _, err := exec.LookPath(browser); err == nil {
				return true
			}
		}
		return false
	default:
		return false
	}
}

// GetPlatformInfo returns a map containing details about the current platform's
// browser opening capabilities, including the OS, architecture, and available commands.
//
// Returns:
//   - A map with platform-specific browser support information.
func GetPlatformInfo() map[string]interface{} {
	info := map[string]interface{}{
		"os":        runtime.GOOS,
		"arch":      runtime.GOARCH,
		"available": IsAvailable(),
	}

	switch runtime.GOOS {
	case "darwin":
		info["default_command"] = "open"
	case "windows":
		info["default_command"] = "rundll32"
	case "linux":
		browsers := []string{"xdg-open", "x-www-browser", "www-browser", "firefox", "chromium", "google-chrome"}
		var availableBrowsers []string
		for _, browser := range browsers {
			if _, err := exec.LookPath(browser); err == nil {
				availableBrowsers = append(availableBrowsers, browser)
			}
		}
		info["available_browsers"] = availableBrowsers
		if len(availableBrowsers) > 0 {
			info["default_command"] = availableBrowsers[0]
		}
	}

	return info
}