package main

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

	"github.com/spf13/cobra"
)

var cleanCmd = &cobra.Command{
	Use:   "clean",
	Short: "Remove all QVM data",
	Long: `Completely remove all QVM state, images, and caches.

This is a destructive operation that removes:
- Base image
- VM overlay and state
- Build caches (cargo, pnpm, sccache)
- Configuration and flake

WARNING: This cannot be undone!`,
	Run: func(cmd *cobra.Command, args []string) {
		logging.Warn("This will delete ALL QVM data")
		fmt.Printf("  - Data directory:  %s\n", config.DataDir)
		fmt.Printf("  - State directory: %s\n", config.StateDir)
		fmt.Printf("  - Cache directory: %s\n", config.CacheDir)
		fmt.Printf("  - Config directory: %s\n", config.ConfigDir)
		fmt.Println("")
		logging.Warn("This operation CANNOT be undone!")
		fmt.Println("")

		fmt.Print("Are you absolutely sure? [y/N] ")
		var response string
		fmt.Scanln(&response)

		if response != "y" && response != "Y" {
			logging.Info("Clean cancelled")
			return
		}

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

		logging.Info("Removing QVM data directories...")

		dirs := []struct {
			path string
			name string
		}{
			{config.DataDir, "Data directory"},
			{config.StateDir, "State directory"},
			{config.CacheDir, "Cache directory"},
			{config.ConfigDir, "Config directory"},
		}

		for _, dir := range dirs {
			if _, err := os.Stat(dir.path); err == nil {
				logging.Info(fmt.Sprintf("  - Deleting: %s", dir.path))
				if err := os.RemoveAll(dir.path); err != nil {
					logging.Error(fmt.Sprintf("Failed to delete %s: %v", dir.name, err))
					os.Exit(1)
				}
			}
		}

		logging.Info("QVM cleaned successfully!")
		fmt.Println("")
		fmt.Println("All QVM data has been removed from your system.")
		fmt.Println("Next run of 'qvm start' will initialize everything from scratch.")
		fmt.Println("")
	},
}
