package main

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"git.vdhsn.com/barretthousen/barretthousen/src/lib/kernel"
	api "git.vdhsn.com/barretthousen/barretthousen/src/runner/api/grpc"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/backoff"
	"google.golang.org/grpc/credentials/insecure"
)

type ProxyAdminApp struct {
	LogLevel  kernel.LogLevel `yaml:"log_level" env:"BH_LOG_LEVEL" env-default:"0" yaml-default:"0"`
	Port      int             `yaml:"port" env:"PROXY_ADMIN_PORT"`
	Endpoints struct {
		Runner string `yaml:"runner" env:"RUNNER_ENDPOINT"`
	} `yaml:"endpoints" env:"PROXY_ADMIN_SERVICES"`
}

func (app *ProxyAdminApp) Start(ctx context.Context) error {
	grpcMux := runtime.NewServeMux()
	err := api.RegisterRunnerHandlerFromEndpoint(ctx, grpcMux, app.Endpoints.Runner, []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		grpc.WithConnectParams(grpc.ConnectParams{
			Backoff: backoff.Config{
				MaxDelay: time.Second * 3,
			},
			MinConnectTimeout: time.Second,
		}),
	})
	if err != nil {
		return err
	}

	kernel.TraceLog.Printf("%+v", app)

	httpServer := &http.Server{
		Addr:              fmt.Sprintf("0.0.0.0:%d", app.Port),
		ReadHeaderTimeout: time.Second,
		Handler: http.StripPrefix("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			kernel.TraceLog.Printf("{ \"Client\": \"%s\", \"Path\":\"%s\"} ", r.RemoteAddr, r.URL.Path)
			grpcMux.ServeHTTP(w, r)
		})),
	}

	kernel.InfoLog.Printf("Starting HTTP proxy @ %q", httpServer.Addr)

	return httpServer.ListenAndServe()
}

func (app *ProxyAdminApp) OnStop(ctx context.Context) {
}

func (app *ProxyAdminApp) GetLogLevel() kernel.LogLevel { return app.LogLevel }

func main() {
	kernel.Run(context.Background(), &ProxyAdminApp{
		LogLevel: kernel.LevelTrace,
		Port:     80,
	})
}
