package setup

import (
	"net"
	"os"
	"strings"
)

// DetectLocalIPs returns the host's LAN IP addresses.
// Inside a Docker container, the network interfaces only show the bridge IP
// (e.g. 172.18.0.4), which is useless for users. Instead, we:
// 1. Check HOST_IP env var (set by docker-compose.yml)
// 2. Fall back to interface enumeration as last resort
func DetectLocalIPs() []string {
	// Option 1: explicit HOST_IP from environment
	if hostIP := os.Getenv("HOST_IP"); hostIP != "" {
		return []string{hostIP}
	}

	// Option 2: fallback to interface enumeration (works on bare metal)
	return detectInterfaceIPs()
}

func detectInterfaceIPs() []string {
	ifaces, err := net.Interfaces()
	if err != nil {
		return nil
	}

	var ips []string
	for _, iface := range ifaces {
		// Skip down, loopback, and Docker/container interfaces
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			continue
		}
		name := strings.ToLower(iface.Name)
		if strings.HasPrefix(name, "docker") || strings.HasPrefix(name, "br-") ||
			strings.HasPrefix(name, "veth") || strings.HasPrefix(name, "lo") {
			continue
		}

		addrs, err := iface.Addrs()
		if err != nil {
			continue
		}
		for _, addr := range addrs {
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}
			if ip == nil || ip.IsLoopback() || ip.To4() == nil {
				continue // skip non-IPv4
			}
			ips = append(ips, ip.String())
		}
	}

	return ips
}
