// scripts/set-tracker-cookie is a tiny operator helper that writes a tracker
// session cookie into the age-encrypted secrets store. Until Phase 2 ships
// the in-UI secrets editor, this is the documented path to register a
// cookie for a tracker adapter to pick up.
//
// Usage:
//   go run ./scripts/set-tracker-cookie -id mam -cookie "mam_id=…"
//   go run ./scripts/set-tracker-cookie -id mam -file /path/to/cookie.txt
//
// The flags follow the same age-key discovery order as the main binary, so
// the helper works against a running deployment without further config.
package main

import (
	"context"
	"database/sql"
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/operator/command-center/internal/scrape"
	"github.com/operator/command-center/internal/secrets"

	_ "modernc.org/sqlite"
)

func main() {
	id := flag.String("id", "", "tracker id (matches the id in trackers.yaml)")
	cookie := flag.String("cookie", "", "literal Cookie header value, e.g. mam_id=…")
	cookieFile := flag.String("file", "", "read cookie value from file instead of -cookie")
	dbPath := flag.String("db", "./data/command-center.db", "SQLite database path")
	keyPath := flag.String("age-key", "", "age identity file path (empty = discovery order per DECISIONS.md D5)")
	flag.Parse()

	if *id == "" || (*cookie == "" && *cookieFile == "") {
		fmt.Fprintln(os.Stderr, "usage: set-tracker-cookie -id <id> -cookie <value>  (or -file <path>)")
		os.Exit(2)
	}

	value := *cookie
	if *cookieFile != "" {
		b, err := os.ReadFile(*cookieFile)
		if err != nil {
			die("read cookie file: %v", err)
		}
		value = strings.TrimSpace(string(b))
	}
	if value == "" {
		die("empty cookie value")
	}

	db, err := sql.Open("sqlite", *dbPath)
	if err != nil {
		die("open sqlite %s: %v", *dbPath, err)
	}
	defer db.Close()

	store, err := secrets.New(db, secrets.Config{
		IdentityFile:  *keyPath,
		AllowGenerate: false, // refuse to generate from a CLI helper
	})
	if err != nil {
		die("secrets store: %v", err)
	}

	ctx := context.Background()
	if err := store.Set(ctx, scrape.CookieSecretKey(*id), []byte(value)); err != nil {
		die("write secret: %v", err)
	}
	fmt.Printf("cookie stored for tracker %q (key=%s, %d bytes)\n",
		*id, scrape.CookieSecretKey(*id), len(value))
}

func die(format string, args ...any) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
	os.Exit(1)
}
