package main

import (
	"context"
	"flag"
	"fmt"
	"log/slog"
	"os"

	"archivmail/config"
	"archivmail/internal/storage"
)

// runRecompress walks the mail store and gzip-compresses any file that is not
// yet compressed. Files are replaced atomically (write to temp, then rename).
//
// Usage: archivmail recompress [--config path] [--dry-run]
func runRecompress(args []string) {
	fset := flag.NewFlagSet("recompress", flag.ExitOnError)
	configPath := fset.String("config", "/etc/archivmail/config.yml", "path to config file")
	dryRun := fset.Bool("dry-run", false, "simulate without writing changes")
	_ = fset.Parse(args)

	logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))

	cfg, err := config.Load(*configPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: load config: %v\n", err)
		os.Exit(1)
	}

	storeCfg := storage.Config{
		Dir:             cfg.Storage.StorePath,
		Keyfile:         cfg.Storage.Keyfile,
		DSN:             cfg.Database.DSN(),
		CompressEnabled: true,
	}
	mailStore, err := storage.New(storeCfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: storage init: %v\n", err)
		os.Exit(1)
	}
	defer mailStore.Close()

	if *dryRun {
		logger.Info("recompress: DRY-RUN — keine Änderungen werden gespeichert")
	}

	stats, err := mailStore.Recompress(context.Background(), *dryRun, logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: recompress: %v\n", err)
		os.Exit(1)
	}

	logger.Info("recompress: abgeschlossen",
		"total", stats.Total,
		"compressed", stats.Compressed,
		"already_compressed", stats.AlreadyCompressed,
		"skipped_errors", stats.Errors,
		"bytes_saved_mb", fmt.Sprintf("%.1f MB", float64(stats.BytesSaved)/1024/1024),
	)
}
