package main

import (
	"encoding/json"
	"flag"
	"fmt"
)

func cmdCPEScores(args []string) error {
	fs := flag.NewFlagSet("cpe-scores", flag.ExitOnError)
	jsonMode := fs.Bool("json", false, "emit raw API JSON")
	if err := fs.Parse(args); err != nil {
		return err
	}
	c, err := NewClient()
	if err != nil {
		return err
	}
	var raw []byte
	if err := c.get(apiPrefix+"/cpe_radio_scores", nil, &raw); err != nil {
		return err
	}
	if *jsonMode {
		return printJSON(raw)
	}
	var arr []CPERadioScore
	if err := json.Unmarshal(raw, &arr); err != nil {
		var one CPERadioScore
		if err2 := json.Unmarshal(raw, &one); err2 == nil {
			arr = []CPERadioScore{one}
		} else {
			return fmt.Errorf("decode cpe-scores: %w (body: %s)", err, truncate(string(raw), 200))
		}
	}
	tw := newTab()
	fmt.Fprintln(tw, "NAME\tSTATUS\tAP\tSITE\tRF\tBV\tFW")
	for _, s := range arr {
		fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%.1f\t%.1f\t%s\n",
			s.Name, s.Status, s.APName, s.APSiteName,
			s.RFScore, s.BusinessValue, s.Firmware)
	}
	return tw.Flush()
}
