// scripts/set-automation-token writes an automation tool's API token into
// the age-encrypted secrets store. Mirrors the Phase 1/Phase 3 helpers.
package main

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

	"github.com/operator/command-center/internal/integrations/autobrr"
	"github.com/operator/command-center/internal/secrets"

	_ "modernc.org/sqlite"
)

func main() {
	id := flag.String("id", "", "automation tool id (matches automation-tools.yaml)")
	token := flag.String("token", "", "API token plaintext")
	dbPath := flag.String("db", "./data/command-center.db", "SQLite database path")
	keyPath := flag.String("age-key", "", "age identity file path (empty = discovery)")
	flag.Parse()

	if *id == "" || *token == "" {
		fmt.Fprintln(os.Stderr, "usage: set-automation-token -id <id> -token <token>")
		os.Exit(2)
	}

	db, err := sql.Open("sqlite", *dbPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "open sqlite %s: %v\n", *dbPath, err)
		os.Exit(1)
	}
	defer db.Close()

	store, err := secrets.New(db, secrets.Config{
		IdentityFile:  *keyPath,
		AllowGenerate: false,
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "secrets: %v\n", err)
		os.Exit(1)
	}

	if err := store.Set(context.Background(), autobrr.APITokenSecretKey(*id), []byte(*token)); err != nil {
		fmt.Fprintf(os.Stderr, "write secret: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("api token stored for automation tool %q (key=%s, %d bytes)\n",
		*id, autobrr.APITokenSecretKey(*id), len(*token))
}
