package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"runtime"
	"time"
)

type TestResponse struct {
	Status      string    `json:"status"`
	Message     string    `json:"message"`
	OS          string    `json:"os"`
	Arch        string    `json:"arch"`
	GoVersion   string    `json:"go_version"`
	PID         int       `json:"pid"`
	NumCPU      int       `json:"num_cpu"`
	Goroutines  int       `json:"goroutines"`
	AllocRAM_MB float64   `json:"alloc_ram_mb"`
	Timestamp   time.Time `json:"timestamp"`
}

func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8088"
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		var m runtime.MemStats
		runtime.ReadMemStats(&m)

		resp := TestResponse{
			Status:      "SUCCESS",
			Message:     "Selamat! cPanel / CloudLinux Anda 100% mendukung eksekusi binary Golang.",
			OS:          runtime.GOOS,
			Arch:        runtime.GOARCH,
			GoVersion:   runtime.Version(),
			PID:         os.Getpid(),
			NumCPU:      runtime.NumCPU(),
			Goroutines:  runtime.NumGoroutine(),
			AllocRAM_MB: float64(m.Alloc) / 1024 / 1024,
			Timestamp:   time.Now(),
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(resp)
	})

	http.HandleFunc("/stop", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprintf(w, `{"status":"STOPPED","message":"Proses uji coba Go dihentikan."}`)
		go func() {
			time.Sleep(500 * time.Millisecond)
			os.Exit(0)
		}()
	})

	addr := "127.0.0.1:" + port
	log.Printf("Golang cPanel Test Server berjalan di http://%s (PID: %d)", addr, os.Getpid())
	if err := http.ListenAndServe(addr, nil); err != nil {
		log.Fatalf("Gagal bind port: %v", err)
	}
}
