package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"text/tabwriter"
)

// newTab returns a tabwriter on stdout configured to match uisp/main.go.
func newTab() *tabwriter.Writer {
	return tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
}

// printJSON writes raw bytes (already JSON) verbatim followed by a
// newline. Used by --json mode to preserve the API's exact response.
func printJSON(raw []byte) error {
	_, err := os.Stdout.Write(raw)
	if err != nil {
		return err
	}
	if len(raw) == 0 || raw[len(raw)-1] != '\n' {
		_, err = io.WriteString(os.Stdout, "\n")
	}
	return err
}

// printMergedJSON emits a synthetic paginated envelope around items
// gathered across multiple pages by listAll. The shape mirrors the
// per-page response shape so downstream `jq` scripts keep working.
func printMergedJSON(items []json.RawMessage, p Paginator) error {
	out := struct {
		Data      []json.RawMessage `json:"data"`
		Paginator Paginator         `json:"paginator"`
	}{Data: items, Paginator: p}
	b, err := json.Marshal(out)
	if err != nil {
		return err
	}
	return printJSON(b)
}

// printSingleJSON marshals an arbitrary value as JSON. Used by `get`
// subcommands when --json is set.
func printSingleJSON(v any) error {
	b, err := json.Marshal(v)
	if err != nil {
		return err
	}
	return printJSON(b)
}

// fmtSpeed renders kbps as "-" if 0, else the integer.
func fmtSpeed(kbps int64) string {
	if kbps == 0 {
		return "-"
	}
	return fmt.Sprintf("%d", kbps)
}
