package main

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var version = "0.1.0"

func main() {
	root := &cobra.Command{
		Use:   "drift",
		Short: "dd0c/drift agent — IaC drift detection",
		Long:  "Detects infrastructure drift by comparing Terraform state against live cloud resources.",
	}

	root.AddCommand(checkCmd())
	root.AddCommand(watchCmd())
	root.AddCommand(versionCmd())

	if err := root.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func checkCmd() *cobra.Command {
	var (
		stateFile  string
		endpoint   string
		apiKey     string
		stackName  string
		scrubMode  string
	)

	cmd := &cobra.Command{
		Use:   "check",
		Short: "Run a one-shot drift check against Terraform state",
		RunE: func(cmd *cobra.Command, args []string) error {
			return runCheck(stateFile, endpoint, apiKey, stackName, scrubMode)
		},
	}

	cmd.Flags().StringVar(&stateFile, "state", "", "Path to terraform.tfstate (or S3 URI)")
	cmd.Flags().StringVar(&endpoint, "endpoint", "https://api.dd0c.dev", "dd0c SaaS endpoint")
	cmd.Flags().StringVar(&apiKey, "api-key", os.Getenv("DD0C_API_KEY"), "API key for dd0c SaaS")
	cmd.Flags().StringVar(&stackName, "stack", "", "Stack name identifier")
	cmd.Flags().StringVar(&scrubMode, "scrub", "strict", "Secret scrubbing mode: strict|permissive|off")
	cmd.MarkFlagRequired("state")
	cmd.MarkFlagRequired("stack")

	return cmd
}

func watchCmd() *cobra.Command {
	var (
		sqsQueue  string
		endpoint  string
		apiKey    string
		interval  int
	)

	cmd := &cobra.Command{
		Use:   "watch",
		Short: "Watch for CloudTrail events via SQS and detect drift in real-time",
		RunE: func(cmd *cobra.Command, args []string) error {
			return runWatch(sqsQueue, endpoint, apiKey, interval)
		},
	}

	cmd.Flags().StringVar(&sqsQueue, "sqs-queue", "", "SQS queue URL for CloudTrail events")
	cmd.Flags().StringVar(&endpoint, "endpoint", "https://api.dd0c.dev", "dd0c SaaS endpoint")
	cmd.Flags().StringVar(&apiKey, "api-key", os.Getenv("DD0C_API_KEY"), "API key")
	cmd.Flags().IntVar(&interval, "interval", 60, "Poll interval in seconds")
	cmd.MarkFlagRequired("sqs-queue")

	return cmd
}

func versionCmd() *cobra.Command {
	return &cobra.Command{
		Use:   "version",
		Short: "Print agent version",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf("dd0c/drift agent v%s\n", version)
		},
	}
}

func runCheck(stateFile, endpoint, apiKey, stackName, scrubMode string) error {
	fmt.Printf("Checking drift for stack %q from %s\n", stackName, stateFile)
	// TODO: Wire up scanner → scrubber → reporter pipeline
	return nil
}

func runWatch(sqsQueue, endpoint, apiKey string, interval int) error {
	fmt.Printf("Watching SQS queue %s (poll every %ds)\n", sqsQueue, interval)
	// TODO: SQS consumer loop → scanner → reporter
	return nil
}
