package main

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

	"github.com/disintegration/imaging"
)

func main() {
	dir := "./uploads/items"
	files, err := os.ReadDir(dir)
	if err != nil {
		log.Fatal(err)
	}

	for _, f := range files {
		if f.IsDir() {
			continue
		}

		if f.Name() == "background.png" {
			continue
		}

		ext := strings.ToLower(filepath.Ext(f.Name()))
		if ext != ".jpg" && ext != ".jpeg" && ext != ".png" {
			continue
		}

		path := filepath.Join(dir, f.Name())

		info, _ := f.Info()
		oldSize := info.Size()

		img, err := imaging.Open(path)
		if err != nil {
			fmt.Printf("Ошибка открытия %s: %v\n", f.Name(), err)
			continue
		}

		resized := imaging.Resize(img, 1200, 0, imaging.Lanczos)

		err = imaging.Save(resized, path, imaging.JPEGQuality(82))
		if err != nil {
			fmt.Printf("Ошибка записи %s: %v\n", f.Name(), err)
			continue
		}

		newInfo, _ := os.Stat(path)
		newSize := newInfo.Size()

		fmt.Printf("%s: %d КБ -> %d КБ\n", f.Name(), oldSize/1024, newSize/1024)
	}

	fmt.Println("Готово")
}
