// SPDX-License-Identifier: GPL-3.0-or-later

// Package cli provides the export-key command.
package cli

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

	"github.com/spf13/cobra"
)

// ExportKeyOptions contains options for the export-key command.
type ExportKeyOptions struct {
	Output string
	Format string
}

// newExportKeyCommand creates the export-key command.
func (c *CLI) newExportKeyCommand() *cobra.Command {
	opts := &ExportKeyOptions{}

	cmd := &cobra.Command{
		Use:   "export-key",
		Short: "Export backup key file",
		Long: `Export your backup key file to a new location.

Use this to:
- Create additional backup copies
- Transfer to a USB drive
- Generate a QR code for paper backup

IMPORTANT: Keep your backup key file safe. Without it, you cannot
access your backups or account.`,
		Example: `  # Export to USB drive
  privatebackup export-key --output /media/usb/privatebackup-key.pem

  # Generate QR code for paper backup (future feature)
  privatebackup export-key --output backup-qr.png --format qr`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.runExportKey(opts)
		},
	}

	flags := cmd.Flags()
	flags.StringVarP(&opts.Output, "output", "o", "", "Where to save key file (required)")
	flags.StringVar(&opts.Format, "format", "pem", "Output format: pem, qr")

	_ = cmd.MarkFlagRequired("output")

	return cmd
}

// runExportKey executes the export-key command.
func (c *CLI) runExportKey(opts *ExportKeyOptions) error {
	// Check format
	if opts.Format != "pem" && opts.Format != "qr" {
		return fmt.Errorf("invalid format: %s (expected: pem or qr)", opts.Format)
	}

	if opts.Format == "qr" {
		return fmt.Errorf("QR code export is not yet implemented")
	}

	// Find the source key file
	sourceKeyPath := filepath.Join(c.configMgr.GetConfigDir(), "privatebackup-key.pem")
	if _, err := os.Stat(sourceKeyPath); os.IsNotExist(err) {
		c.renderer.Error("No account configured")
		c.renderer.Info("Run 'privatebackup init' to create an account, or")
		c.renderer.Info("Run 'privatebackup restore-account --key-file <path>' to restore one.")
		return fmt.Errorf("no account configured (run init first)")
	}

	// Read the key file
	keyData, err := os.ReadFile(sourceKeyPath)
	if err != nil {
		return fmt.Errorf("failed to read key file: %w", err)
	}

	// Expand output path
	outputPath := expandPath(opts.Output)

	// Ensure output directory exists
	outputDir := filepath.Dir(outputPath)
	if outputDir != "" && outputDir != "." {
		if err := os.MkdirAll(outputDir, 0700); err != nil {
			return fmt.Errorf("failed to create output directory: %w", err)
		}
	}

	// Check if output file already exists
	if _, err := os.Stat(outputPath); err == nil {
		confirmed, err := c.prompter.Confirm(
			fmt.Sprintf("File %s already exists. Overwrite?", outputPath),
			false,
		)
		if err != nil {
			return err
		}
		if !confirmed {
			return fmt.Errorf("export cancelled")
		}
	}

	// Write the key file
	if err := os.WriteFile(outputPath, keyData, 0600); err != nil {
		return fmt.Errorf("failed to write key file: %w", err)
	}

	c.renderer.Success(fmt.Sprintf("Backup key file saved to: %s", outputPath))
	c.renderer.Newline()
	c.renderer.Warning("Remember: This file is the ONLY way to recover your data.")
	c.renderer.Info("Store it somewhere safe, separate from your computer.")

	return nil
}
