package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/urfave/cli/v3"
	tlog "tangled.org/core/log"
	"tangled.org/core/spindle"
)

func main() {
	cmd := &cli.Command{
		Name:  "spindle",
		Usage: "spindle continuous integration runner",
		Commands: []*cli.Command{
			Run(),
			adminCmd,
		},
		DefaultCommand: "run",
	}

	logger := tlog.New("spindle")
	slog.SetDefault(logger)

	ctx := context.Background()
	ctx = tlog.IntoContext(ctx, logger)

	if err := cmd.Run(ctx, os.Args); err != nil {
		logger.Error(err.Error())
		os.Exit(-1)
	}
}

func Run() *cli.Command {
	return &cli.Command{
		Name:  "run",
		Usage: "run the spindle server",
		Action: func(ctx context.Context, cmd *cli.Command) error {
			return spindle.Run(ctx)
		},
	}
}

var adminCmd = &cli.Command{
	Name: "admin",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:  "url",
			Value: "http://localhost:6555",
			Usage: "spindle server url",
		},
		&cli.StringFlag{
			Name:    "password",
			Usage:   "admin password",
			Sources: cli.EnvVars("SPINDLE_SERVER_ADMIN_PASSWORD"),
		},
	},
	Commands: []*cli.Command{
		{
			Name:      "allow",
			Usage:     "allow a did to use this spindle",
			ArgsUsage: "<did>",
			Action: func(ctx context.Context, c *cli.Command) error {
				return spindle.AdminAllowMember(ctx, c.String("url"), c.String("password"), c.Args().First())
			},
		},
		{
			Name:      "block",
			Usage:     "block a did from using this spindle",
			ArgsUsage: "<did>",
			Action: func(ctx context.Context, c *cli.Command) error {
				return spindle.AdminBlockMember(ctx, c.String("url"), c.String("password"), c.Args().First())
			},
		},
	},
}
