package helper

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"runtime"
	"strings"
	"syscall"

	"github.com/gookit/goutil/dump"
)

func IsIPAddr(ip string) bool {
	ipaddr := net.ParseIP(NormaliseIPAddr(ip))
	return ipaddr != nil
}

func NormaliseIPAddr(ip string) string {
	if strings.HasSuffix(ip, "/32") && strings.Contains(ip, ".") { // single host (IPv4)
		ip = strings.TrimSuffix(ip, "/32")
	} else {
		ip = strings.TrimSuffix(ip, "/128") // single host (IPv6)
	}

	return ip
}

// fqdn format to domain format
func FtoD(fqdn string) string {
	return strings.TrimSuffix(fqdn, ".")
}

func StartHTTP() {
	log.Printf("Starting HTTP at :80")
	http.ListenAndServe(":80", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "DEV port 80 OK")
	}))
}

func P2(input ...any) {
	dump.Print(input...)
}
func P(input ...any) {
	fmt.Println(input...)
}

func PrintOldStyleMetrics() {
	runtime.GOMAXPROCS(4)
	fmt.Printf("Operating system is: %s\n", runtime.GOOS)
	// Get number of go routines, max os threads allocated to process and host number of cpus
	numGoroutines := runtime.NumGoroutine()
	fmt.Printf("The program is using %d go routines\n", numGoroutines)
	maxThreads := runtime.GOMAXPROCS(0)
	fmt.Printf("The program is configured to %d max threads ", maxThreads)
	numCPUs := runtime.NumCPU()
	fmt.Printf("- the host has %d cpus", numCPUs)

}

func Start(app func()) {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	// done := make(chan bool, 1)

	go func() {
		app()
	}()

	<-sigs

}
