package collector

import (
	"os/exec"
	"strings"
)

type Route struct {
	Destination string `json:"destination"`
	Gateway     string `json:"gateway"`
	Flags       string `json:"flags"`
	Interface   string `json:"interface"`
}

// CollectRoutes liest die Routing-Tabelle via netstat -rn
func CollectRoutes() []Route {
	out, err := exec.Command("/usr/bin/netstat", "-rn", "-f", "inet").Output()
	if err != nil {
		return nil
	}

	var routes []Route
	inTable := false

	for _, line := range strings.Split(string(out), "\n") {
		trimmed := strings.TrimSpace(line)

		// Header erkennen
		if strings.HasPrefix(trimmed, "Destination") {
			inTable = true
			continue
		}
		if !inTable || trimmed == "" {
			continue
		}

		fields := strings.Fields(trimmed)
		if len(fields) < 4 {
			continue
		}

		route := Route{
			Destination: fields[0],
			Gateway:     fields[1],
			Flags:       fields[2],
		}

		// Interface ist typischerweise das letzte oder vorletzte Feld
		// FreeBSD netstat -rn: Destination Gateway Flags Refs Use Netif Expire
		// Mindestens 6 Felder fuer Netif
		if len(fields) >= 6 {
			route.Interface = fields[5]
		} else if len(fields) >= 4 {
			route.Interface = fields[len(fields)-1]
		}

		routes = append(routes, route)
	}

	return routes
}
