// Copyright 2026 printing-press-golden. Licensed under Apache-2.0. See LICENSE.
// Generated by CLI Printing Press (https://github.com/mvanhorn/cli-printing-press). DO NOT EDIT.

package cli

import (
	"fmt"
	"github.com/spf13/cobra"
	"os"
	"printing-press-rich-pp-cli/internal/config"
)

func newAuthCmd(flags *rootFlags) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "auth",
		Short: "Manage authentication for Printing Press Rich",
		RunE:  parentNoSubcommandRunE(flags),
	}

	cmd.AddCommand(newAuthSetupCmd(flags))
	cmd.AddCommand(newAuthStatusCmd(flags))
	cmd.AddCommand(newAuthSetTokenCmd(flags))
	cmd.AddCommand(newAuthLogoutCmd(flags))

	return cmd
}

// newAuthSetupCmd prints concrete steps for getting a credential. Side-effect
// rule: print by default, --launch opt-in to open the URL, short-circuit when
// the verifier is running this in a sandboxed subprocess.
func newAuthSetupCmd(_ *rootFlags) *cobra.Command {
	var launch bool
	cmd := &cobra.Command{
		Use:     "setup",
		Short:   "Print steps for obtaining a credential (use --launch to open the URL)",
		Example: "  printing-press-rich-pp-cli auth setup\n  printing-press-rich-pp-cli auth setup --launch",
		RunE: func(cmd *cobra.Command, args []string) error {
			w := cmd.OutOrStdout()
			fmt.Fprintln(w, "No setup URL is configured for this CLI; check the API's docs.")
			fmt.Fprintln(w, "")
			fmt.Fprintln(w, "Then set:")
			fmt.Fprintln(w, "  export RICH_AUTH_API_KEY=\"<your-token>\"")
			fmt.Fprintln(w, "  export RICH_AUTH_OPTIONAL_TOKEN=\"<your-token>\"")
			fmt.Fprintln(w, "  export RICH_AUTH_BOT_TOKEN=\"<your-token>\"")
			fmt.Fprintln(w, "  export RICH_AUTH_USER_TOKEN=\"<your-token>\"")
			fmt.Fprintln(w, "  printing-press-rich-pp-cli auth set-token <token>")
			if !launch {
				return nil
			}
			fmt.Fprintln(cmd.ErrOrStderr(), "no setup URL configured; cannot launch")
			return nil
		},
	}
	cmd.Flags().BoolVar(&launch, "launch", false, "Open the setup URL in your default browser")
	return cmd
}

func newAuthStatusCmd(flags *rootFlags) *cobra.Command {
	return &cobra.Command{
		Use:     "status",
		Short:   "Show authentication status",
		Example: "  printing-press-rich-pp-cli auth status",
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}

			w := cmd.OutOrStdout()
			header := cfg.AuthHeader()
			authed := header != ""
			// JSON envelope: {authenticated, verified, source, config}. When not
			// authenticated, write the envelope first then return authErr
			// so exit code carries the auth-failure signal.
			if flags.asJSON {
				out := map[string]any{
					"authenticated": authed,
					"verified":      false,
					"source":        cfg.AuthSource,
					"config":        cfg.Path,
				}
				if printErr := printJSONFiltered(w, out, flags); printErr != nil {
					return printErr
				}
				if !authed {
					return authErr(fmt.Errorf("no credentials configured"))
				}
				return nil
			}
			if !authed {
				fmt.Fprintln(w, red("Not authenticated"))
				fmt.Fprintln(w, "")
				fmt.Fprintln(w, "Set your token:")
				fmt.Fprintln(w, "  export RICH_AUTH_API_KEY=\"your-token-here\"")
				fmt.Fprintln(w, "  export RICH_AUTH_OPTIONAL_TOKEN=\"your-token-here\"")
				fmt.Fprintln(w, "  export RICH_AUTH_BOT_TOKEN=\"your-token-here\"")
				fmt.Fprintln(w, "  export RICH_AUTH_USER_TOKEN=\"your-token-here\"")
				fmt.Fprintf(w, "  printing-press-rich-pp-cli auth set-token <token>\n")
				return authErr(fmt.Errorf("no credentials configured"))
			}

			fmt.Fprintln(w, green("Credentials present (not verified)"))
			fmt.Fprintf(w, "  Source: %s\n", cfg.AuthSource)
			fmt.Fprintf(w, "  Config: %s\n", cfg.Path)
			return nil
		},
	}
}

func newAuthSetTokenCmd(flags *rootFlags) *cobra.Command {
	return &cobra.Command{
		Use:     "set-token <token>",
		Short:   "Save an API token to the config file",
		Example: "  printing-press-rich-pp-cli auth set-token YOUR_TOKEN_HERE",
		Args:    cobra.ExactArgs(1),
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}

			// Clear any legacy auth_header so AuthHeader() falls through to
			// the newly-saved credential. Without this, a pre-existing
			// auth_header value (common after regenerate) shadows the saved
			// token and set-token silently has no effect. Silent clear (no
			// log line): a masked-tail variant could leak token bytes through
			// scripted dogfood that captures stderr.
			cfg.AuthHeaderVal = ""
			// api_key auth: AuthHeader() reads the env-var-derived field, not
			// AccessToken. Writing the token to AccessToken via SaveTokens
			// would persist the bytes but leave doctor reporting "not
			// configured" — the slot the header builder consults stays empty.
			if err := cfg.SaveCredential(args[0]); err != nil {
				return configErr(fmt.Errorf("saving token: %w", err))
			}

			// JSON envelope: {saved, config_path}.
			if flags.asJSON {
				return printJSONFiltered(cmd.OutOrStdout(), map[string]any{
					"saved":       true,
					"config_path": cfg.Path,
				}, flags)
			}
			fmt.Fprintf(cmd.OutOrStdout(), "Token saved to %s\n", cfg.Path)
			return nil
		},
	}
}

func newAuthLogoutCmd(flags *rootFlags) *cobra.Command {
	return &cobra.Command{
		Use:     "logout",
		Short:   "Clear stored credentials",
		Example: "  printing-press-rich-pp-cli auth logout",
		RunE: func(cmd *cobra.Command, args []string) error {
			cfg, err := config.Load(flags.configPath)
			if err != nil {
				return configErr(err)
			}

			if err := cfg.ClearTokens(); err != nil {
				return configErr(fmt.Errorf("clearing tokens: %w", err))
			}

			// Identify which (if any) auth env var is still exported so the
			// JSON envelope and the human prose can both surface it.
			envStillSet := ""
			if envStillSet == "" && os.Getenv("RICH_AUTH_API_KEY") != "" {
				envStillSet = "RICH_AUTH_API_KEY"
			}
			if envStillSet == "" && os.Getenv("RICH_AUTH_CLIENT_ID") != "" {
				envStillSet = "RICH_AUTH_CLIENT_ID"
			}
			if envStillSet == "" && os.Getenv("RICH_AUTH_CLIENT_SECRET") != "" {
				envStillSet = "RICH_AUTH_CLIENT_SECRET"
			}
			if envStillSet == "" && os.Getenv("RICH_AUTH_SESSION_COOKIE") != "" {
				envStillSet = "RICH_AUTH_SESSION_COOKIE"
			}
			if envStillSet == "" && os.Getenv("RICH_AUTH_OPTIONAL_TOKEN") != "" {
				envStillSet = "RICH_AUTH_OPTIONAL_TOKEN"
			}
			if envStillSet == "" && os.Getenv("RICH_AUTH_BOT_TOKEN") != "" {
				envStillSet = "RICH_AUTH_BOT_TOKEN"
			}
			if envStillSet == "" && os.Getenv("RICH_AUTH_USER_TOKEN") != "" {
				envStillSet = "RICH_AUTH_USER_TOKEN"
			}

			// JSON envelope: {cleared: true, note?: "<env_var> env var is still set"}.
			if flags.asJSON {
				out := map[string]any{"cleared": true}
				if envStillSet != "" {
					out["note"] = envStillSet + " env var is still set"
				}
				return printJSONFiltered(cmd.OutOrStdout(), out, flags)
			}

			if envStillSet != "" {
				fmt.Fprintf(cmd.OutOrStdout(), "Config cleared. Note: %s env var is still set.\n", envStillSet)
				return nil
			}
			fmt.Fprintln(cmd.OutOrStdout(), "Logged out. Credentials cleared.")
			return nil
		},
	}
}
