package main

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

	"github.com/stevec/fancywin/internal/config"
	"github.com/stevec/fancywin/internal/platform"
	"gopkg.in/yaml.v3"
)

const version = "0.5.1"

var backgroundMode bool

func main() {
	exe, err := os.Executable()
	if err != nil {
		fatal(err)
	}
	configPath := flag.String("config", config.DefaultPath(exe), "path to YAML configuration")
	check := flag.Bool("check", false, "validate configuration and exit")
	printDefault := flag.Bool("print-default", false, "print a default configuration and exit")
	showVersion := flag.Bool("version", false, "print version and exit")
	debug := flag.Bool("debug", false, "log window move and snap diagnostics")
	flag.Parse()

	if *showVersion {
		fmt.Println("fancywin", version)
		return
	}
	if *printDefault {
		b, err := yaml.Marshal(config.Default())
		if err != nil {
			fatal(err)
		}
		_, _ = os.Stdout.Write(b)
		return
	}
	backgroundMode = !*check && !*debug
	if backgroundMode {
		platform.PrepareBackground()
	}
	cfg, err := config.Load(*configPath)
	if err != nil {
		fatal(fmt.Errorf("%s: %w", filepath.Clean(*configPath), err))
	}
	if *check {
		fmt.Printf("configuration OK: %s\n", filepath.Clean(*configPath))
		return
	}
	fmt.Printf("fancywin %s using %s\n", version, filepath.Clean(*configPath))
	if err := platform.Run(*configPath, cfg, *debug); err != nil {
		fatal(err)
	}
}

func fatal(err error) {
	fmt.Fprintln(os.Stderr, "fancywin:", err)
	if backgroundMode {
		platform.ShowError("FancyWin", err.Error())
	}
	os.Exit(1)
}
