// scripts/set-torrent-client-password writes a torrent client's WebUI
// password into the age-encrypted secrets store. Phase 3 ships this as the
// operator path to register credentials; Phase 15 may surface an in-UI
// editor once the threat model around secret writes is settled.
package main

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

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

	_ "modernc.org/sqlite"
)

func main() {
	id := flag.String("id", "", "torrent client id (matches the id in torrent-clients.yaml)")
	password := flag.String("password", "", "WebUI password")
	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 == "" || *password == "" {
		fmt.Fprintln(os.Stderr, "usage: set-torrent-client-password -id <id> -password <pw>")
		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(), qbit.CredentialSecretKey(*id), []byte(*password)); err != nil {
		fmt.Fprintf(os.Stderr, "write secret: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("password stored for torrent client %q (key=%s, %d bytes)\n",
		*id, qbit.CredentialSecretKey(*id), len(*password))
}
