package kernelcat

import (
	_ "embed"
	"encoding/json"
	"fmt"
	"os"
)

//go:embed catalog.json
var embeddedCatalog []byte

// Catalog is the published list of kernel bundles banger can pull. It ships
// embedded in the banger binary and is updated across releases; Phase 5
// wires CI to regenerate it.
type Catalog struct {
	Version int        `json:"version"`
	Entries []CatEntry `json:"entries"`
}

// CatEntry describes one downloadable kernel bundle.
type CatEntry struct {
	Name          string `json:"name"`
	Distro        string `json:"distro,omitempty"`
	Arch          string `json:"arch,omitempty"`
	KernelVersion string `json:"kernel_version,omitempty"`
	TarballURL    string `json:"tarball_url"`
	TarballSHA256 string `json:"tarball_sha256"`
	SizeBytes     int64  `json:"size_bytes,omitempty"`
	Description   string `json:"description,omitempty"`
}

// LoadEmbedded returns the catalog compiled into this banger binary.
func LoadEmbedded() (Catalog, error) {
	return ParseCatalog(embeddedCatalog)
}

// ParseCatalog decodes a catalog.json payload. An empty payload is valid
// and returns a zero Catalog.
func ParseCatalog(data []byte) (Catalog, error) {
	var cat Catalog
	if len(data) == 0 {
		return cat, nil
	}
	if err := json.Unmarshal(data, &cat); err != nil {
		return Catalog{}, fmt.Errorf("parse catalog: %w", err)
	}
	return cat, nil
}

// Lookup returns the catalog entry matching name, or os.ErrNotExist.
func (c Catalog) Lookup(name string) (CatEntry, error) {
	for _, e := range c.Entries {
		if e.Name == name {
			return e, nil
		}
	}
	return CatEntry{}, os.ErrNotExist
}
