package main

import (
	"epochsilicon/pkg/log"
	"epochsilicon/pkg/service"
	"epochsilicon/pkg/ui"
	"epochsilicon/pkg/utils"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"github.com/Masterminds/semver/v3"
	"strings"
)

const appVersion = "1.0.9"

func main() {
	log.SetupLogging()

	PEApp := app.NewWithID("com.burkey.epochsilicon")
	PEWindow := PEApp.NewWindow("EpochSilicon v" + appVersion)
	PEWindow.Resize(fyne.NewSize(650, 500))
	PEWindow.SetFixedSize(true)

	go func() {
		prefs, _ := utils.LoadPrefs()
		updateInfo, updateAvailable, err := utils.CheckForUpdateWithAssets(semver.MustParse(appVersion))
		if err != nil {
			log.Debugf("Failed to check for updates: %v", err)
			return
		}

		if !updateAvailable {
			log.Debugf("No updates available")
			return
		}

		latestVersion := strings.TrimPrefix(updateInfo.TagName, "v")
		log.Debugf("Update available: current=%s, latest=%s", appVersion, latestVersion)

		// Skip if user has suppressed this version
		if prefs.SuppressedUpdateVersion == latestVersion {
			log.Debugf("Update suppressed by user: %s", latestVersion)
			return
		}

		// Show enhanced update dialog
		ui.ShowUpdateDialog(updateInfo, appVersion, PEWindow)
	}()

	content := ui.CreateUI(PEWindow)
	PEWindow.SetContent(content)

	// Set up cleanup when window closes
	PEWindow.SetCloseIntercept(func() {
		log.Debug("Application closing, cleaning up RosettaX87 service...")
		service.CleanupService()
		PEApp.Quit()
	})

	PEWindow.ShowAndRun()
}
