package main

import (
	_ "embed"
	"encoding/json"
	"strings"

	"hamlog/internal/applog"
)

//go:embed changelog.json
var changelogJSON []byte

// ChangelogEntry is one release's user-facing notes, in English and French. It's
// shown once on the first launch after an update (the "What's new" dialog),
// derived from the release's commit history.
type ChangelogEntry struct {
	Version string   `json:"version"`
	Date    string   `json:"date"`
	EN      []string `json:"en"`
	FR      []string `json:"fr"`
}

const keyChangelogSeen = "changelog.last_seen_version"

func loadChangelog() []ChangelogEntry {
	var out []ChangelogEntry
	if err := json.Unmarshal(changelogJSON, &out); err != nil {
		applog.Printf("changelog: parse failed: %v", err)
	}
	return out
}

// GetChangelog returns every changelog entry up to the running version (newest
// first), without touching the "seen" marker — for a "What's new" button that
// reopens the notes on demand.
func (a *App) GetChangelog() []ChangelogEntry {
	out := []ChangelogEntry{}
	for _, e := range loadChangelog() {
		if strings.TrimSpace(e.Version) == "" || versionLess(appVersion, e.Version) {
			continue
		}
		out = append(out, e)
	}
	return out
}

// GetWhatsNew returns the changelog entries the operator hasn't seen yet — the
// notes for every version newer than the last one they ran, up to the current
// build — and records the current version as seen so it pops exactly once per
// update. Empty when there's nothing new.
func (a *App) GetWhatsNew() []ChangelogEntry {
	if a.settings == nil {
		return nil
	}
	lastSeen, _ := a.settings.GetGlobal(a.ctx, keyChangelogSeen)
	cur := appVersion
	a.setSettingGlobal(keyChangelogSeen, cur) // advance the marker now

	out := []ChangelogEntry{}
	for _, e := range loadChangelog() {
		if strings.TrimSpace(e.Version) == "" {
			continue
		}
		if versionLess(cur, e.Version) {
			continue // don't preview notes for a version newer than we run
		}
		if lastSeen == "" {
			// First run of the feature (fresh install, or upgrade from a build that
			// predates it): show only the CURRENT version's notes, once.
			if e.Version == cur {
				out = append(out, e)
			}
			continue
		}
		if versionLess(lastSeen, e.Version) {
			out = append(out, e)
		}
	}
	return out
}
