package agent

import (
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
)

const tokenFile = ".cursor-token"

func ReadCachedToken(configDir string) string {
	p := filepath.Join(configDir, tokenFile)
	data, err := os.ReadFile(p)
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(data))
}

func WriteCachedToken(configDir, token string) {
	p := filepath.Join(configDir, tokenFile)
	_ = os.WriteFile(p, []byte(token), 0600)
}

func ReadKeychainToken() string {
	if runtime.GOOS != "darwin" {
		return ""
	}
	out, err := exec.Command("security", "find-generic-password", "-s", "cursor-access-token", "-w").Output()
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(out))
}
