package cli

import (
	"fmt"
	"time"

	"github.com/urfave/cli/v2"
	"sneak.berlin/go/mfer/internal/log"
	"sneak.berlin/go/mfer/mfer"
)

func (mfa *CLIApp) listManifestOperation(ctx *cli.Context) error {
	// Default to ErrorLevel for clean output
	log.SetLevel(log.ErrorLevel)

	longFormat := ctx.Bool("long")
	print0 := ctx.Bool("print0")

	// Find manifest file
	var manifestPath string
	var err error

	if ctx.Args().Len() > 0 {
		arg := ctx.Args().Get(0)
		info, statErr := mfa.Fs.Stat(arg)
		if statErr == nil && info.IsDir() {
			manifestPath, err = findManifest(mfa.Fs, arg)
			if err != nil {
				return err
			}
		} else {
			manifestPath = arg
		}
	} else {
		manifestPath, err = findManifest(mfa.Fs, ".")
		if err != nil {
			return err
		}
	}

	// Load manifest
	manifest, err := mfer.NewManifestFromFile(mfa.Fs, manifestPath)
	if err != nil {
		return fmt.Errorf("failed to load manifest: %w", err)
	}

	files := manifest.Files()

	// Determine line ending
	lineEnd := "\n"
	if print0 {
		lineEnd = "\x00"
	}

	for _, f := range files {
		if longFormat {
			mtime := time.Unix(f.Mtime.Seconds, int64(f.Mtime.Nanos))
			_, _ = fmt.Fprintf(mfa.Stdout, "%d\t%s\t%s%s", f.Size, mtime.Format(time.RFC3339), f.Path, lineEnd)
		} else {
			_, _ = fmt.Fprintf(mfa.Stdout, "%s%s", f.Path, lineEnd)
		}
	}

	return nil
}
