package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"os"
	"slices"
	"strings"
	"time"

	"github.com/spf13/cobra"
	"gopkg.in/yaml.v2"

	incus "github.com/lxc/incus/v6/client"
	"github.com/lxc/incus/v6/internal/i18n"
	"github.com/lxc/incus/v6/internal/instance"
	"github.com/lxc/incus/v6/shared/api"
	cli "github.com/lxc/incus/v6/shared/cmd"
	"github.com/lxc/incus/v6/shared/termios"
)

type cmdSnapshot struct {
	global *cmdGlobal
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshot) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("snapshot")
	cmd.Short = i18n.G("Manage instance snapshots")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Manage instance snapshots`))

	// Create.
	snapshotCreateCmd := cmdSnapshotCreate{global: c.global, snapshot: c}
	cmd.AddCommand(snapshotCreateCmd.Command())

	// Delete.
	snapshotDeleteCmd := cmdSnapshotDelete{global: c.global, snapshot: c}
	cmd.AddCommand(snapshotDeleteCmd.Command())

	// List.
	snapshotListCmd := cmdSnapshotList{global: c.global, snapshot: c}
	cmd.AddCommand(snapshotListCmd.Command())

	// Rename.
	snapshotRenameCmd := cmdSnapshotRename{global: c.global, snapshot: c}
	cmd.AddCommand(snapshotRenameCmd.Command())

	// Restore.
	snapshotRestoreCmd := cmdSnapshotRestore{global: c.global, snapshot: c}
	cmd.AddCommand(snapshotRestoreCmd.Command())

	// Show.
	snapshotShowCmd := cmdSnapshotShow{global: c.global, snapshot: c}
	cmd.AddCommand(snapshotShowCmd.Command())

	// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
	cmd.Args = cobra.NoArgs
	cmd.Run = func(cmd *cobra.Command, _ []string) { _ = cmd.Usage() }
	return cmd
}

// Create.
type cmdSnapshotCreate struct {
	global   *cmdGlobal
	snapshot *cmdSnapshot

	flagStateful bool
	flagNoExpiry bool
	flagExpiry   string
	flagReuse    bool
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshotCreate) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("create", i18n.G("[<remote>:]<instance> [<snapshot name>]"))
	cmd.Aliases = []string{"add"}
	cmd.Short = i18n.G("Create instance snapshot")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Create instance snapshots

When --stateful is used, attempt to checkpoint the instance's
running state, including process memory state, TCP connections, ...`))
	cmd.Example = cli.FormatSection("", i18n.G(`incus snapshot create u1 snap0
	Create a snapshot of "u1" called "snap0".

incus snapshot create u1 snap0 < config.yaml
	Create a snapshot of "u1" called "snap0" with the configuration from "config.yaml".`))

	cmd.Flags().BoolVar(&c.flagStateful, "stateful", false, i18n.G("Whether or not to snapshot the instance's running state"))
	cmd.Flags().StringVar(&c.flagExpiry, "expiry", "", i18n.G("Expiry date or time span for the new snapshot"))
	cmd.Flags().BoolVar(&c.flagNoExpiry, "no-expiry", false, i18n.G("Ignore any configured auto-expiry for the instance"))
	cmd.Flags().BoolVar(&c.flagReuse, "reuse", false, i18n.G("If the snapshot name already exists, delete and create a new one"))

	cmd.RunE = c.Run

	cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return c.global.cmpInstances(toComplete)
		}

		return nil, cobra.ShellCompDirectiveNoFileComp
	}

	return cmd
}

// Run runs the actual command logic.
func (c *cmdSnapshotCreate) Run(cmd *cobra.Command, args []string) error {
	var stdinData api.InstanceSnapshotPut
	conf := c.global.conf

	// Quick checks.
	exit, err := c.global.checkArgs(cmd, args, 1, 2)
	if exit {
		return err
	}

	if c.flagNoExpiry && c.flagExpiry != "" {
		return errors.New(i18n.G("Can't use both --no-expiry and --expiry"))
	}

	// If stdin isn't a terminal, read text from it
	if !termios.IsTerminal(getStdinFd()) {
		contents, err := io.ReadAll(os.Stdin)
		if err != nil {
			return err
		}

		err = yaml.Unmarshal(contents, &stdinData)
		if err != nil {
			return err
		}
	}

	var snapname string
	if len(args) < 2 {
		snapname = ""
	} else {
		snapname = args[1]
	}

	remote, name, err := conf.ParseRemote(args[0])
	if err != nil {
		return err
	}

	if instance.IsSnapshot(name) {
		if snapname != "" {
			return fmt.Errorf(i18n.G("Invalid instance name: %s"), name)
		}

		fields := strings.SplitN(name, instance.SnapshotDelimiter, 2)
		name = fields[0]
		snapname = fields[1]
	}

	d, err := conf.GetInstanceServer(remote)
	if err != nil {
		return err
	}

	if c.flagReuse && snapname != "" {
		snap, _, _ := d.GetInstanceSnapshot(name, snapname)
		if snap != nil {
			op, err := d.DeleteInstanceSnapshot(name, snapname)
			if err != nil {
				return err
			}

			err = op.Wait()
			if err != nil {
				return err
			}
		}
	}

	req := api.InstanceSnapshotsPost{
		Name:     snapname,
		Stateful: c.flagStateful,
	}

	if c.flagNoExpiry {
		req.ExpiresAt = &time.Time{}
	} else if c.flagExpiry != "" {
		// Try to parse as a duration.
		expiry, err := instance.GetExpiry(time.Now(), c.flagExpiry)
		if err != nil {
			if !errors.Is(err, instance.ErrInvalidExpiry) {
				return err
			}

			// Fallback to date parsing.
			expiry, err = time.Parse(dateLayout, c.flagExpiry)
			if err != nil {
				return err
			}
		}

		req.ExpiresAt = &expiry
	} else if !stdinData.ExpiresAt.IsZero() {
		req.ExpiresAt = &stdinData.ExpiresAt
	}

	op, err := d.CreateInstanceSnapshot(name, req)
	if err != nil {
		return err
	}

	return op.Wait()
}

// Delete.
type cmdSnapshotDelete struct {
	global   *cmdGlobal
	snapshot *cmdSnapshot

	flagInteractive bool
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshotDelete) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("delete", i18n.G("[<remote>:]<instance> <snapshot name>"))
	cmd.Aliases = []string{"rm", "remove"}
	cmd.Short = i18n.G("Delete instance snapshots")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Delete instance snapshots`))

	cmd.Flags().BoolVarP(&c.flagInteractive, "interactive", "i", false, i18n.G("Require user confirmation"))

	cmd.RunE = c.Run

	cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return c.global.cmpInstances(toComplete)
		}

		return nil, cobra.ShellCompDirectiveNoFileComp
	}

	return cmd
}

// Run runs the actual command logic.
func (c *cmdSnapshotDelete) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.checkArgs(cmd, args, 2, 2)
	if exit {
		return err
	}

	// Parse remote
	resources, err := c.global.parseServers(args[0])
	if err != nil {
		return err
	}

	// Process with deletion.
	if c.flagInteractive {
		err := c.promptDelete(resources[0].name, args[1])
		if err != nil {
			return err
		}
	}

	err = c.doDelete(resources[0].server, resources[0].name, args[1])
	if err != nil {
		return err
	}

	return nil
}

func (c *cmdSnapshotDelete) promptDelete(instName string, name string) error {
	reader := bufio.NewReader(os.Stdin)
	fmt.Printf(i18n.G("Remove snapshot %s from %s (yes/no): "), name, instName)
	input, _ := reader.ReadString('\n')
	input = strings.TrimSuffix(input, "\n")

	if !slices.Contains([]string{i18n.G("yes")}, strings.ToLower(input)) {
		return errors.New(i18n.G("User aborted delete operation"))
	}

	return nil
}

func (c *cmdSnapshotDelete) doDelete(d incus.InstanceServer, instName string, name string) error {
	var op incus.Operation
	var err error

	// Snapshot delete
	op, err = d.DeleteInstanceSnapshot(instName, name)
	if err != nil {
		return err
	}

	return op.Wait()
}

// List.
type cmdSnapshotList struct {
	global   *cmdGlobal
	snapshot *cmdSnapshot

	flagFormat  string
	flagColumns string
}

type snapshotColumn struct {
	Name string
	Data func(api.InstanceSnapshot) string
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshotList) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("list", i18n.G("[<remote>:]<instance>"))
	cmd.Aliases = []string{"ls"}
	cmd.Short = i18n.G("List instance snapshots")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`List instance snapshots

Default column layout: nTEs

== Columns ==
The -c option takes a comma separated list of arguments that control
which network zone attributes to output when displaying in table or csv
format.

Column arguments are either pre-defined shorthand chars (see below),
or (extended) config keys.

Commas between consecutive shorthand chars are optional.

Pre-defined column shorthand chars:
  n - Name
  T - Taken At
  E - Expires At
  s - Stateful`))

	cmd.Flags().StringVarP(&c.flagFormat, "format", "f", c.global.defaultListFormat(), i18n.G(`Format (csv|json|table|yaml|compact|markdown), use suffix ",noheader" to disable headers and ",header" to enable it if missing, e.g. csv,header`)+"``")
	cmd.Flags().StringVarP(&c.flagColumns, "columns", "c", defaultSnapshotColumns, i18n.G("Columns")+"``")

	cmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
		return cli.ValidateFlagFormatForListOutput(cmd.Flag("format").Value.String())
	}

	cmd.RunE = c.Run

	cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return c.global.cmpInstances(toComplete)
		}

		return nil, cobra.ShellCompDirectiveNoFileComp
	}

	return cmd
}

const defaultSnapshotColumns = "nTEs"

func (c *cmdSnapshotList) parseColumns() ([]snapshotColumn, error) {
	columnsShorthandMap := map[rune]snapshotColumn{
		'n': {i18n.G("NAME"), c.nameColumnData},
		'T': {i18n.G("TAKEN AT"), c.takenAtColumnData},
		'E': {i18n.G("EXPIRES AT"), c.expiresAtColumnData},
		's': {i18n.G("STATEFUL"), c.statefulColumnData},
	}

	columnList := strings.Split(c.flagColumns, ",")
	columns := []snapshotColumn{}

	for _, columnEntry := range columnList {
		if columnEntry == "" {
			return nil, fmt.Errorf(i18n.G("Empty column entry (redundant, leading or trailing command) in '%s'"), c.flagColumns)
		}

		for _, columnRune := range columnEntry {
			column, ok := columnsShorthandMap[columnRune]
			if !ok {
				return nil, fmt.Errorf(i18n.G("Unknown column shorthand char '%c' in '%s'"), columnRune, columnEntry)
			}

			columns = append(columns, column)
		}
	}

	return columns, nil
}

func (c *cmdSnapshotList) nameColumnData(snapshot api.InstanceSnapshot) string {
	return snapshot.Name
}

func (c *cmdSnapshotList) takenAtColumnData(snapshot api.InstanceSnapshot) string {
	if snapshot.CreatedAt.IsZero() {
		return " "
	}

	return snapshot.CreatedAt.Local().Format(dateLayout)
}

func (c *cmdSnapshotList) expiresAtColumnData(snapshot api.InstanceSnapshot) string {
	if snapshot.ExpiresAt.IsZero() {
		return " "
	}

	return snapshot.ExpiresAt.Local().Format(dateLayout)
}

func (c *cmdSnapshotList) statefulColumnData(snapshot api.InstanceSnapshot) string {
	strStateful := "NO"
	if snapshot.Stateful {
		strStateful = "YES"
	}

	return strStateful
}

// Run runs the actual command logic.
func (c *cmdSnapshotList) Run(cmd *cobra.Command, args []string) error {
	conf := c.global.conf

	// Quick checks.
	exit, err := c.global.checkArgs(cmd, args, 1, 1)
	if exit {
		return err
	}

	remote, instanceName, err := conf.ParseRemote(args[0])
	if err != nil {
		return err
	}

	d, err := conf.GetInstanceServer(remote)
	if err != nil {
		return err
	}

	snapshots, err := d.GetInstanceSnapshots(instanceName)
	if err != nil {
		return err
	}

	// Parse column flags.
	columns, err := c.parseColumns()
	if err != nil {
		return err
	}

	data := [][]string{}
	for _, snap := range snapshots {
		line := []string{}
		for _, column := range columns {
			line = append(line, column.Data(snap))
		}

		data = append(data, line)
	}

	header := []string{}
	for _, column := range columns {
		header = append(header, column.Name)
	}

	return cli.RenderTable(os.Stdout, c.flagFormat, header, data, snapshots)
}

// Rename.
type cmdSnapshotRename struct {
	global   *cmdGlobal
	snapshot *cmdSnapshot
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshotRename) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("rename", i18n.G("[<remote>:]<instance> <old snapshot name> <new snapshot name>"))
	cmd.Short = i18n.G("Rename instance snapshots")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Rename instance snapshots`))

	cmd.RunE = c.Run

	cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return c.global.cmpInstances(toComplete)
		}

		if len(args) == 1 {
			return c.global.cmpInstanceSnapshots(args[0])
		}

		return nil, cobra.ShellCompDirectiveNoFileComp
	}

	return cmd
}

// Run runs the actual command logic.
func (c *cmdSnapshotRename) Run(cmd *cobra.Command, args []string) error {
	conf := c.global.conf

	// Quick checks.
	exit, err := c.global.checkArgs(cmd, args, 3, 3)
	if exit {
		return err
	}

	// Check the remotes
	remote, instanceName, err := conf.ParseRemote(args[0])
	if err != nil {
		return err
	}

	d, err := conf.GetInstanceServer(remote)
	if err != nil {
		return err
	}

	// Snapshot rename
	op, err := d.RenameInstanceSnapshot(instanceName, args[1], api.InstanceSnapshotPost{Name: args[2]})
	if err != nil {
		return err
	}

	return op.Wait()
}

// Restore.
type cmdSnapshotRestore struct {
	global   *cmdGlobal
	snapshot *cmdSnapshot

	flagStateful bool
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshotRestore) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("restore", i18n.G("[<remote>:]<instance> <snapshot name>"))
	cmd.Short = i18n.G("Restore instance snapshots")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Restore instance from snapshots

If --stateful is passed, then the running state will be restored too.`))
	cmd.Example = cli.FormatSection("", i18n.G(
		`incus snapshot restore u1 snap0
    Restore instance u1 to snapshot snap0`))

	cmd.Flags().BoolVar(&c.flagStateful, "stateful", false, i18n.G("Whether or not to restore the instance's running state from snapshot (if available)"))

	cmd.RunE = c.Run

	cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return c.global.cmpInstances(toComplete)
		}

		if len(args) == 1 {
			return c.global.cmpInstanceSnapshots(args[0])
		}

		return nil, cobra.ShellCompDirectiveNoFileComp
	}

	return cmd
}

// Run runs the actual command logic.
func (c *cmdSnapshotRestore) Run(cmd *cobra.Command, args []string) error {
	conf := c.global.conf

	// Quick checks.
	exit, err := c.global.checkArgs(cmd, args, 2, 2)
	if exit {
		return err
	}

	// Connect to the daemon.
	remote, name, err := conf.ParseRemote(args[0])
	if err != nil {
		return err
	}

	d, err := conf.GetInstanceServer(remote)
	if err != nil {
		return err
	}

	// Setup the snapshot restore
	snapname := args[1]
	if !instance.IsSnapshot(snapname) {
		snapname = fmt.Sprintf("%s/%s", name, snapname)
	}

	req := api.InstancePut{
		Restore:  snapname,
		Stateful: c.flagStateful,
	}

	// Restore the snapshot
	op, err := d.UpdateInstance(name, req, "")
	if err != nil {
		return err
	}

	return op.Wait()
}

// Show.
type cmdSnapshotShow struct {
	global   *cmdGlobal
	snapshot *cmdSnapshot
}

// Command returns a cobra.Command for use with (*cobra.Command).AddCommand.
func (c *cmdSnapshotShow) Command() *cobra.Command {
	cmd := &cobra.Command{}
	cmd.Use = cli.Usage("show", i18n.G("[<remote>:]<instance> <snapshot>"))
	cmd.Short = i18n.G("Show instance snapshot configuration")
	cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
		`Show instance snapshot configuration`))

	cmd.RunE = c.Run

	cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		if len(args) == 0 {
			return c.global.cmpInstances(toComplete)
		}

		if len(args) == 1 {
			return c.global.cmpInstanceSnapshots(args[0])
		}

		return nil, cobra.ShellCompDirectiveNoFileComp
	}

	return cmd
}

// Run runs the actual command logic.
func (c *cmdSnapshotShow) Run(cmd *cobra.Command, args []string) error {
	// Quick checks.
	exit, err := c.global.checkArgs(cmd, args, 2, 2)
	if exit {
		return err
	}

	// Parse remote
	resources, err := c.global.parseServers(args[0])
	if err != nil {
		return err
	}

	resource := resources[0]

	// Snapshot
	snap, _, err := resource.server.GetInstanceSnapshot(resource.name, args[1])
	if err != nil {
		return err
	}

	data, err := yaml.Marshal(&snap)
	if err != nil {
		return err
	}

	fmt.Printf("%s", data)

	return nil
}
