package hdmistat

import (
	"fmt"
	"time"

	"git.eeqj.de/sneak/hdmistat/internal/layout"
	"git.eeqj.de/sneak/hdmistat/internal/statcollector"
	"github.com/spf13/cobra"
)

const (
	percentMultiplier = 100.0
)

// newInfoCmd creates the info command
func (c *CLI) newInfoCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "info",
		Short: "Display system information in terminal",
		Long:  `Display current system information in the terminal without using the framebuffer.`,
		Run:   c.runInfo,
	}
}

func (c *CLI) runInfo(_ *cobra.Command, _ []string) {
	collector := statcollector.NewSystemCollector(c.log)

	c.log.Info("collecting system information")
	info, err := collector.Collect()
	if err != nil {
		c.log.Error("collecting system info", "error", err)
		return
	}

	// Display system information
	fmt.Println("=== System Information ===")
	fmt.Printf("Hostname: %s\n", info.Hostname)
	fmt.Printf("Uptime: %s\n", layout.FormatDuration(info.Uptime.Seconds()))
	fmt.Println()

	// Memory
	fmt.Println("=== Memory ===")
	fmt.Printf("Total: %s\n", layout.FormatBytes(info.MemoryTotal))
	fmt.Printf("Used: %s (%.1f%%)\n",
		layout.FormatBytes(info.MemoryUsed),
		float64(info.MemoryUsed)/float64(info.MemoryTotal)*percentMultiplier)
	fmt.Printf("Free: %s\n", layout.FormatBytes(info.MemoryFree))
	fmt.Println()

	// CPU
	fmt.Println("=== CPU ===")
	for i, percent := range info.CPUPercent {
		fmt.Printf("CPU %d: %.1f%%\n", i, percent)
	}
	fmt.Println()

	// Temperature
	if len(info.Temperature) > 0 {
		fmt.Println("=== Temperature ===")
		for sensor, temp := range info.Temperature {
			fmt.Printf("%s: %.1f°C\n", sensor, temp)
		}
		fmt.Println()
	}

	// Disk
	fmt.Println("=== Disk Usage ===")
	for _, disk := range info.DiskUsage {
		fmt.Printf("%s: %s / %s (%.1f%%)\n",
			disk.Path,
			layout.FormatBytes(disk.Used),
			layout.FormatBytes(disk.Total),
			disk.UsedPercent)
	}
	fmt.Println()

	// Network
	fmt.Println("=== Network ===")
	for _, net := range info.Network {
		fmt.Printf("%s:\n", net.Name)
		for _, ip := range net.IPAddresses {
			fmt.Printf("  IP: %s\n", ip)
		}
		fmt.Printf("  TX: %s\n", layout.FormatBytes(net.BytesSent))
		fmt.Printf("  RX: %s\n", layout.FormatBytes(net.BytesRecv))
	}

	fmt.Printf("\nCollected at: %s\n", info.CollectedAt.Format(time.RFC3339))
}
