package cmd

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"


	"git.wntrmute.dev/kyle/arca/internal/config"
	"git.wntrmute.dev/kyle/arca/internal/udisks"
	"github.com/godbus/dbus/v5"
	"github.com/spf13/cobra"
	"gopkg.in/yaml.v3"
)

var forceInit bool

var initCmd = &cobra.Command{
	Use:   "init",
	Short: "Generate config from detected LUKS devices",
	Long:  "Scans for LUKS-encrypted devices, excludes the root filesystem, and writes a config file with passphrase as the default unlock method.",
	RunE:  runInit,
}

func init() {
	initCmd.Flags().BoolVarP(&forceInit, "force", "f", false, "overwrite existing config file")
	rootCmd.AddCommand(initCmd)
}

func runInit(cmd *cobra.Command, args []string) error {
	cfgPath := config.Path()

	if !forceInit {
		if _, err := os.Stat(cfgPath); err == nil {
			return fmt.Errorf("config already exists at %s (use --force to overwrite)", cfgPath)
		}
	}

	client, err := udisks.NewClient()
	if err != nil {
		return fmt.Errorf("connecting to udisks2: %w", err)
	}
	defer client.Close()

	encrypted, err := client.ListEncryptedDevices()
	if err != nil {
		return err
	}

	rootBacking, err := client.RootBackingDevices()
	if err != nil {
		return fmt.Errorf("detecting root device: %w", err)
	}

	cfg := config.Config{
		Devices: make(map[string]config.DeviceConfig),
	}

	for _, dev := range encrypted {
		if isRootBacking(dev.ObjectPath, rootBacking) {
			fmt.Fprintf(os.Stderr, "Skipping %s (root filesystem)\n", dev.DevicePath)
			continue
		}

		alias := aliasFromUUID(dev.UUID)
		cfg.Devices[alias] = config.DeviceConfig{
			UUID:    dev.UUID,
			Methods: []string{"passphrase"},
		}
		fmt.Fprintf(os.Stderr, "Found %s (UUID %s) -> alias %q\n", dev.DevicePath, dev.UUID, alias)
	}

	if len(cfg.Devices) == 0 {
		fmt.Println("No non-root LUKS devices found.")
		return nil
	}

	data, err := yaml.Marshal(&cfg)
	if err != nil {
		return fmt.Errorf("marshaling config: %w", err)
	}

	if err := os.MkdirAll(filepath.Dir(cfgPath), 0o755); err != nil {
		return fmt.Errorf("creating config directory: %w", err)
	}

	if err := os.WriteFile(cfgPath, data, 0o644); err != nil {
		return fmt.Errorf("writing config: %w", err)
	}

	fmt.Printf("Config written to %s\n", cfgPath)
	return nil
}

func isRootBacking(path dbus.ObjectPath, rootDevices []dbus.ObjectPath) bool {
	for _, r := range rootDevices {
		if path == r {
			return true
		}
	}
	return false
}

func aliasFromUUID(uuid string) string {
	// Use first 8 chars of UUID as a stable alias.
	// "b8b2f8e3-4cde-4aca-a96e-df9274019f9f" -> "b8b2f8e3"
	clean := strings.ReplaceAll(uuid, "-", "")
	if len(clean) > 8 {
		clean = clean[:8]
	}
	return clean
}
