package main

import (
	"fmt"
	"os"
	"qvm/internal/config"
	"qvm/internal/logging"
	"qvm/internal/vm"

	"github.com/spf13/cobra"
)

var resetCmd = &cobra.Command{
	Use:   "reset",
	Short: "Reset VM to fresh state",
	Long: `Delete the VM overlay and workspace registry.

This returns the VM to a clean state based on the base image.
The base image itself is not deleted.

All cache directories are preserved.`,
	Run: func(cmd *cobra.Command, args []string) {
		logging.Info("Resetting VM state...")

		if vm.IsRunning() {
			logging.Info("Stopping VM...")
			stopResult := vm.Stop()
			if stopResult.IsError() {
				logging.Error(stopResult.Error().Error())
				os.Exit(1)
			}
		}

		if _, err := os.Stat(config.Overlay); err == nil {
			logging.Info(fmt.Sprintf("Deleting overlay: %s", config.Overlay))
			if err := os.Remove(config.Overlay); err != nil {
				logging.Error(fmt.Sprintf("Failed to delete overlay: %v", err))
				os.Exit(1)
			}
		}

		if _, err := os.Stat(config.WorkspacesFile); err == nil {
			logging.Info(fmt.Sprintf("Deleting workspaces registry: %s", config.WorkspacesFile))
			if err := os.Remove(config.WorkspacesFile); err != nil {
				logging.Error(fmt.Sprintf("Failed to delete workspaces: %v", err))
				os.Exit(1)
			}
		}

		logging.Info("Reset complete!")
		fmt.Println("")
		fmt.Println("Next steps:")
		fmt.Println("  - Run 'qvm start' to boot the VM with a fresh overlay")
		fmt.Println("")
	},
}
