package app

import (
	"fmt"
	"strings"

	intpsmux "github.com/crevissepartners/projmux/internal/integrations/psmux"
	intpicker "github.com/crevissepartners/projmux/internal/ui/picker"
)

func psmuxAppConfig(binaryPath string) (string, error) {
	statusGit, err := intpsmux.ProjmuxCommand(binaryPath, "status", "git", "#{pane_current_path}").PowerShell()
	if err != nil {
		return "", fmt.Errorf("render psmux status git command: %w", err)
	}
	projectSwitch, err := intpsmux.ProjmuxCommand(binaryPath, "switch", "--ui=sidebar").PowerShell()
	if err != nil {
		return "", fmt.Errorf("render psmux project switch command: %w", err)
	}
	projectSwitch = strings.Join([]string{
		powerShellEnvAssignment(muxBackendEnvVar, string(muxBackendPSMux)),
		powerShellEnvAssignment(intpicker.BackendEnv, string(intpicker.BackendNative)),
		powerShellEnvAssignment("PROJMUX_NATIVE_LINE_MODE", "1"),
		projectSwitch,
	}, "; ")
	projectSwitchTail := psmuxPowerShellCommandTail(projectSwitch)
	lines := []string{
		"# Generated by projmux. Used by native Windows `projmux.exe shell` with psmux.",
		"# Phase 4B includes only the minimal project switch popup; pane-scoped metadata, session-state replay, and rich hooks remain follow-up.",
		"set -g @projmux_app 1",
		"set -g mouse on",
		"set -g history-limit 10000",
		"set -g status on",
		"set -g status-position bottom",
		"set -g status-interval 5",
		"set -g status-left " + psmuxConfigQuote(" #{session_name} "),
		"set -g status-right " + psmuxConfigQuote("#("+statusGit+")  %Y-%m-%d %H:%M "),
		"set -g window-status-separator \" \"",
		"set -g allow-rename off",
		"set -g automatic-rename on",
		"bind-key -n C-n new-window -c " + psmuxConfigQuote("#{pane_current_path}"),
		"bind-key -n M-1 display-popup -d " + psmuxConfigQuote("#{pane_current_path}") + " -x 0 -y 0 -w 42% -h 100% -T " + psmuxConfigQuote("Projects") + " -E " + projectSwitchTail,
	}
	return strings.Join(lines, "\n") + "\n", nil
}

func psmuxPowerShellCommandTail(script string) string {
	return "powershell -NoProfile -Command " + psmuxConfigQuote(script)
}

func psmuxConfigQuote(value string) string {
	return "\"" + strings.ReplaceAll(value, "\"", "\\\"") + "\""
}

func powerShellEnvAssignment(name, value string) string {
	return "$env:" + name + " = " + powerShellSingleQuote(value)
}

func powerShellSingleQuote(value string) string {
	return "'" + strings.ReplaceAll(value, "'", "''") + "'"
}
