// Send a chat turn with a file attachment, then rename/star the session and
// tidy up the attachment.
//
// StartAgentChatWithFiles posts multipart/form-data; Aiden stores each file
// and gives the agent an attachment://<session_id>/<attachment_id> handle
// instead of the raw bytes (for reference-mode agents) or inlines it (inline
// agents, capped at 3 MiB/file). There is no list-attachments endpoint, so
// the handle only shows up in the turn's own content -- ask the agent to
// repeat it back, or scan the execution debug ZIP. Pass -attachment-id once
// you have one to also exercise download + delete.
//
//	export STACKGEN_URL=https://app.stackgen.com
//	export STACKGEN_TOKEN=stackgen_…
//	export STACKGEN_WORKSPACE_ID=<workspace-uuid>
//	go run ./examples/go/automation/chat-session-attachments.go -agent my-ops-agent
package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"

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

// envOr returns the first non-empty environment variable among keys.
func envOr(keys ...string) string {
	for _, key := range keys {
		if v := strings.TrimSpace(os.Getenv(key)); v != "" {
			return v
		}
	}
	return ""
}

func main() {
	agent := flag.String("agent", "", "existing agent name to chat with")
	attachmentID := flag.String("attachment-id", "", "UUID from a previously seen attachment:// handle; also exercises download + delete")
	flag.Parse()
	if strings.TrimSpace(*agent) == "" {
		fmt.Fprintln(os.Stderr, "-agent is required")
		os.Exit(2)
	}
	base, token, org := envOr("STACKGEN_URL"), envOr("STACKGEN_TOKEN"), envOr("STACKGEN_WORKSPACE_ID", "STACKGEN_PROJECT")
	if base == "" || token == "" || org == "" {
		fmt.Fprintln(os.Stderr, "set STACKGEN_URL, STACKGEN_TOKEN, and STACKGEN_WORKSPACE_ID")
		os.Exit(2)
	}
	client, err := stackgen.NewClient(stackgen.Config{BaseURL: base, APIToken: token, WorkspaceID: org})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	ctx := context.Background()

	run, err := client.Aiden.StartAgentChatWithFiles(ctx, *agent,
		"Summarize the attached file in one sentence.", "",
		[]aiden.ChatFile{{
			Filename:    "sdk-sample-notes.txt",
			Content:     []byte("Deploys succeed when the health check passes within 60s.\n"),
			ContentType: "text/plain",
		}},
	)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Printf("started chat session_id=%s trace_id=%s\n", run.SessionID, run.TraceID)

	if err := client.Aiden.SubscribeExecution(ctx, run.TraceID, func(aiden.ExecutionEvent) error {
		return nil
	}); err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Println("turn complete")

	title := "SDK sample: attachment summary"
	starred := true
	updated, err := client.Aiden.UpdateSessionMetadata(ctx, run.SessionID, aiden.UpdateSessionMetadataRequest{
		Title: &title, Starred: &starred,
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Printf("renamed session title=%v starred=%v\n", updated["title"], updated["starred"])

	if strings.TrimSpace(*attachmentID) == "" {
		fmt.Println("no -attachment-id passed; skipping DownloadSessionAttachment. " +
			"Capture an attachment_id from the agent's reply or the execution debug ZIP, then rerun with -attachment-id.")
		return
	}

	dir, err := os.MkdirTemp("", "sdk-attachment-")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	dest, err := client.Aiden.DownloadSessionAttachment(ctx, run.SessionID, *attachmentID, filepath.Join(dir, "downloaded.txt"))
	if err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Printf("downloaded attachment to %s\n", dest)

	if err := client.Aiden.DeleteSessionAttachments(ctx, run.SessionID); err != nil {
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
	fmt.Printf("deleted all attachments for session_id=%s\n", run.SessionID)
}
