package backup

import (
	"encoding/json"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

// R-833 LAB (not run in CI: needs OFFSITE_LAB_DIR from the lab script). Reads a REAL restic 0.14.0
// repo's `snapshots --json` and the policy's `forget --dry-run --json`, and runs the box's own guard
// with the hub's default cap and with an operator-raised cap. Writes the ids the guard would remove to
// $OFFSITE_LAB_DIR/ids.txt for the lab script to prune. Evidence: audits/backup-close-2026-10-04/partB/.
func TestOffsiteGuard_R833_LabRepo(t *testing.T) {
	dir := os.Getenv("OFFSITE_LAB_DIR")
	if dir == "" {
		t.Skip("lab only: set OFFSITE_LAB_DIR")
	}
	var all []guardSnap
	b, err := os.ReadFile(filepath.Join(dir, "snaps.json"))
	if err != nil {
		t.Fatal(err)
	}
	if err := json.Unmarshal(b, &all); err != nil {
		t.Fatal(err)
	}
	b, err = os.ReadFile(filepath.Join(dir, "plan.json"))
	if err != nil {
		t.Fatal(err)
	}
	var groups []struct {
		Remove []guardSnap `json:"remove"`
	}
	if err := json.Unmarshal(b, &groups); err != nil {
		t.Fatal(err)
	}
	var plan []guardSnap
	for _, g := range groups {
		plan = append(plan, g.Remove...)
	}
	now := time.Now()
	def := len(all) / 2 // the hub's MaxRemove(count): half, minimum 5
	if def < 5 {
		def = 5
	}
	_, refuse := offsiteGuard(all, plan, now, now, def)
	t.Logf("snapshots=%d plan=%d default cap=%d → refusal: %q", len(all), len(plan), def, refuse)
	raised := 0
	if v := os.Getenv("OFFSITE_LAB_RAISED"); v != "" {
		for _, c := range v {
			raised = raised*10 + int(c-'0')
		}
	}
	if raised == 0 {
		return
	}
	ids, refuse2 := offsiteGuard(all, plan, now, now, raised)
	t.Logf("raised cap=%d → %d id(s), refusal: %q", raised, len(ids), refuse2)
	if err := os.WriteFile(filepath.Join(dir, "ids.txt"), []byte(strings.Join(ids, "\n")), 0o600); err != nil {
		t.Fatal(err)
	}
}
