package main

import (
	"fmt"
	"log"
	"slices"

	"gensokyo.uk/nix"
)

func buildAndResolve(ctx nix.Context, name string, installable *string, collective *[]string, flagNixOS bool, args []string) error {
	if err := formatInstallable(name, installable, flagNixOS, args); err != nil {
		return err
	}

	log.Printf("building %q...", *installable)
	if err := nix.Build(ctx, slices.Values([]string{*installable})); err != nil {
		return commandHandlerError(fmt.Sprintf("cannot build: %v", err))
	}

	log.Printf("evaluating %q...", *installable)
	var installables []string
	if v, err := nix.EvalInstantiated(ctx, *installable); err != nil {
		return commandHandlerError(fmt.Sprintf("cannot evaluate: %v", err))
	} else {
		installables = v
	}

	log.Println("building instantiated derivations...")
	if err := nix.Build(ctx, slices.Values(installables)); err != nil {
		return commandHandlerError(fmt.Sprintf("cannot build: %v", err))
	}

	log.Println("collecting store paths...")
	if derivations, err := nix.DerivationShow(ctx, slices.Values(installables)); err != nil {
		return commandHandlerError(fmt.Sprintf("cannot get derivations: %v", err))
	} else {
		*collective = nix.CollectFromDerivations(derivations)
		return nil
	}
}
