// Webhook trigger → wait for session → download session artifact.
//
// Documented on https://appcd-dev.github.io/stackgen-sdk/code-samples/webhook-session-artifact/
//
//	export WEBHOOK_TOKEN='sg_aios_…'
//	go run ./examples/go/webhook/webhook-download-report.go \
//	  -base-url https://app.stackgen.com \
//	  -api-token stackgen_… \
//	  -workspace-id <workspace-uuid> \
//	  -query 'P1 | checkout-api error rate above SLO'
//
// -retry-max controls how many times transient failures (network errors,
// 429, 5xx) are retried with exponential backoff before giving up.
package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/hashicorp/go-retryablehttp"

	stackgen "github.com/appcd-dev/stackgen-sdk/clients/go"
)

func envOr(keys ...string) string {
	for _, key := range keys {
		if v := strings.TrimSpace(os.Getenv(key)); v != "" {
			return v
		}
	}
	return ""
}

func main() {
	baseURL := flag.String("base-url", envOr("STACKGEN_URL", "STACKGEN_BASE_URL"), "Mothership URL (no /guild suffix)")
	apiToken := flag.String("api-token", envOr("STACKGEN_TOKEN", "STACKGEN_API_TOKEN"), "API token (stackgen_…)")
	orgID := flag.String("workspace-id", envOr("STACKGEN_WORKSPACE_ID", "STACKGEN_PROJECT", "STACKGEN_PROJECT_ID", "STACKGEN_ORG_ID", "ORG_ID"), "Workspace UUID (sent as orgId)")
	flag.StringVar(orgID, "org-id", *orgID, "Deprecated: use -workspace-id")
	webhookToken := flag.String("webhook-token", "", "Webhook token (sg_aios_…); or set WEBHOOK_TOKEN")
	query := flag.String("query", "", "Alert text or payload for the webhook")
	artifactName := flag.String("artifact-name", "session-report.md", "Session artifact filename to download")
	outputPath := flag.String("output-path", "session-report.md", "Local path to write the artifact")
	timeoutSeconds := flag.Int("timeout-seconds", 1800, "Overall timeout")
	pollIntervalSeconds := flag.Int("poll-interval-seconds", 5, "Poll interval")
	retryMax := flag.Int("retry-max", 4, "Max retries for transient HTTP failures (network errors, 429, 5xx)")
	flag.Parse()

	wh := strings.TrimSpace(*webhookToken)
	if wh == "" {
		wh = envOr("STACKGEN_WEBHOOK_TOKEN", "WEBHOOK_TOKEN")
	}
	if strings.TrimSpace(*baseURL) == "" || strings.TrimSpace(*apiToken) == "" || strings.TrimSpace(*orgID) == "" {
		fmt.Fprintln(os.Stderr, "error: set -base-url/-api-token/-workspace-id or STACKGEN_URL/STACKGEN_TOKEN/STACKGEN_WORKSPACE_ID")
		os.Exit(2)
	}
	if wh == "" {
		fmt.Fprintln(os.Stderr, "error: set -webhook-token or WEBHOOK_TOKEN")
		os.Exit(2)
	}
	if strings.TrimSpace(*query) == "" {
		fmt.Fprintln(os.Stderr, "error: -query is required")
		os.Exit(2)
	}

	rc := retryablehttp.NewClient()
	rc.RetryMax = *retryMax
	rc.Logger = nil
	httpClient := rc.StandardClient()

	client, err := stackgen.NewClient(stackgen.Config{
		BaseURL:             *baseURL,
		APIToken:            *apiToken,
		WebhookToken:        wh,
		WorkspaceID:         *orgID,
		ArtifactName:        *artifactName,
		OutputPath:          *outputPath,
		TimeoutSeconds:      *timeoutSeconds,
		PollIntervalSeconds: *pollIntervalSeconds,
		HTTPClient:          httpClient,
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(*timeoutSeconds)*time.Second)
	defer cancel()
	result, err := client.Aiden.RunWebhookAndDownloadReport(ctx, *query)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stderr, "webhook_id=%s session_id=%s output=%s\n", result.WebhookID, result.SessionID, result.OutputPath)
}
