package agent

import (
	"context"
	"cursor-api-proxy/internal/config"
	"cursor-api-proxy/internal/process"
	"os"
	"path/filepath"
)

func init() {
	process.MaxModeFn = RunMaxModePreflight
}

func cacheTokenForAccount(configDir string) {
	if configDir == "" {
		return
	}
	token := ReadKeychainToken()
	if token != "" {
		WriteCachedToken(configDir, token)
	}
}

func AccountsDir() string {
	home := os.Getenv("HOME")
	if home == "" {
		home = os.Getenv("USERPROFILE")
	}
	return filepath.Join(home, ".cursor-api-proxy", "accounts")
}

func RunAgentSync(cfg config.BridgeConfig, workspaceDir string, cmdArgs []string, tempDir, configDir string, ctx context.Context) (process.RunResult, error) {
	opts := process.RunOptions{
		Cwd:       workspaceDir,
		TimeoutMs: cfg.TimeoutMs,
		MaxMode:   cfg.MaxMode,
		ConfigDir: configDir,
		Ctx:       ctx,
	}

	result, err := process.Run(cfg.AgentBin, cmdArgs, opts)

	cacheTokenForAccount(configDir)
	if tempDir != "" {
		os.RemoveAll(tempDir)
	}

	return result, err
}

func RunAgentStreamWithContext(cfg config.BridgeConfig, workspaceDir string, cmdArgs []string, onLine func(string), tempDir, configDir string, ctx context.Context) (process.StreamResult, error) {
	opts := process.RunStreamingOptions{
		RunOptions: process.RunOptions{
			Cwd:       workspaceDir,
			TimeoutMs: cfg.TimeoutMs,
			MaxMode:   cfg.MaxMode,
			ConfigDir: configDir,
			Ctx:       ctx,
		},
		OnLine: onLine,
	}

	result, err := process.RunStreaming(cfg.AgentBin, cmdArgs, opts)

	cacheTokenForAccount(configDir)
	if tempDir != "" {
		os.RemoveAll(tempDir)
	}

	return result, err
}
