package cli

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/spf13/cobra"

	"git.cloudinit.dev/coreci/orca/internal/daemon"
	"git.cloudinit.dev/coreci/orca/internal/engine"
	"git.cloudinit.dev/coreci/orca/internal/store"
)

var (
	daemonAddr string
	pprofAddr  string
)

var daemonCmd = &cobra.Command{
	Use:   "daemon",
	Short: "Run the orca daemon (HTTP API + health checks)",
	Long: `Start the orca daemon. Listens on the configured address for health, API, and dispatch requests.

Deprecated: v0.9 re-architecture replaces the orca daemon with SSH-push to
bare servers (R-001 — no orca binary on servers). The daemon is repurposed to
drain-and-stop in v0.10-P05 and scheduled for deletion in v0.10-P14. See
.ciagent/PRD_v0.9.md.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		warnDeprecated("orca daemon is deprecated in v0.9 and will be repurposed to 'drain-and-stop' in v0.10-P05; the v0.9 re-architecture (R-001) removes the orca binary from servers — see .ciagent/PRD_v0.9.md")
		db, closer, err := openDB()
		if err != nil {
			return err
		}
		defer closer()

		log := newLogger()
		addr := daemonAddr
		if cfg := configFromCtx(cmd.Context()); cfg != nil && cfg.ListenAddr != "" && !cmd.Flags().Changed("addr") {
			addr = cfg.ListenAddr
		}
		srv := daemon.NewServer(daemon.Options{
			DB:        db,
			Log:       log,
			Addr:      addr,
			Actor:     "daemon",
			PprofAddr: pprofAddr,
		})

		// Wire the orca.v1.Dispatch service (v0.2 P02). The executor
		// runs jobs locally; the dispatcher decides local vs peer.
		executor := engine.NewExecutor(store.NewJobRepo(db), store.NewTaskRepo(db), log)
		peers := engine.NewPeerRegistry()
		dispatcher := engine.NewDispatcher(log, store.NewCapacityRepo(db), peers, executor)
		srv.RegisterDispatch(daemon.NewDispatchHandlers(dispatcher, dispatcher.Dedupe()))

		srv.MarkReady()

		errCh := make(chan error, 1)
		go func() {
			err := srv.Start()
			if err != nil && !errors.Is(err, http.ErrServerClosed) {
				errCh <- err
			}
		}()

		fmt.Fprintf(cmd.OutOrStdout(), "✓ orca daemon listening on %s\n", daemonAddr)
		fmt.Fprintln(cmd.OutOrStdout(), "  /healthz                        - liveness")
		fmt.Fprintln(cmd.OutOrStdout(), "  /readyz                         - readiness (db + ready flag)")
		fmt.Fprintln(cmd.OutOrStdout(), "  /v1/status                      - status JSON")
		fmt.Fprintln(cmd.OutOrStdout(), "  /v1/jobs                        - list jobs")
		fmt.Fprintln(cmd.OutOrStdout(), "  /v1/nodes                       - list nodes")
		fmt.Fprintln(cmd.OutOrStdout(), "  /v1/tasks                       - list tasks")
		fmt.Fprintln(cmd.OutOrStdout(), "  /orca.v1.Dispatch/Submit        - cross-node job submit (P02)")
		fmt.Fprintln(cmd.OutOrStdout(), "  /orca.v1.Dispatch/Status        - cross-node job status (P02)")
		if pprofAddr != "" {
			fmt.Fprintf(cmd.OutOrStdout(), "  /debug/pprof/ (pprof)        - %s\n", pprofAddr)
		}
		fmt.Fprintln(cmd.OutOrStdout(), "  press Ctrl+C to stop")

		ctx, stop := signal.NotifyContext(cmd.Context(), os.Interrupt, syscall.SIGTERM)
		defer stop()

		select {
		case <-ctx.Done():
			fmt.Fprintln(cmd.OutOrStdout(), "\nshutting down...")
			shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
			defer cancel()
			return srv.Shutdown(shutdownCtx)
		case err := <-errCh:
			return err
		}
	},
}

func init() {
	daemonCmd.Flags().StringVar(&daemonAddr, "addr", ":8080", "listen address")
	daemonCmd.Flags().StringVar(&pprofAddr, "pprof", "", "enable pprof endpoint on <addr> (e.g. :6060); unauthenticated, operator-only")
	rootCmd.AddCommand(daemonCmd)
}
