// replaycheck replays a single pricing_comparison_logs row through
// the replay-race fingerprint offline. Input is one JSON object on
// stdin (or from a file argument) in the exact shape of a
// model/billing/testdata/replay_backtest.jsonl line — which is itself
// the exact shape of a comparison row's pricing / raw / diffs columns —
// so a suspicious row from the DB or from a fixture drops straight in:
//
//	mysql ... -e "select pricing, raw, diffs from pricing_comparison_logs where id=123" \
//	  | jq -c '.[0]' | go run ./cmd/replaycheck
//
// or against the backtest fixture:
//
//	head -3 model/billing/testdata/replay_backtest.jsonl | \
//	  while read r; do echo "$r" | go run ./cmd/replaycheck; done
//
// Output is the verdict plus the per-stage fingerprint trace: which
// stage carried the exemption, or exactly where it failed closed.
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/pingcap/dbaas/billing2/db/entity"
	"github.com/pingcap/dbaas/billing2/model/billing"
	"github.com/pingcap/dbaas/billing2/model/billing/pipeline"
)

func main() {
	var in io.Reader = os.Stdin
	if len(os.Args) > 1 {
		f, err := os.Open(os.Args[1])
		if err != nil {
			fatal("open input: %v", err)
		}
		defer f.Close()
		in = f
	}

	rawJSON, err := io.ReadAll(in)
	if err != nil {
		fatal("read input: %v", err)
	}
	var row struct {
		ID      int64  `json:"id"`
		Pricing string `json:"pricing"`
		Raw     string `json:"raw"`
		Diffs   string `json:"diffs"`
	}
	if err := json.Unmarshal(rawJSON, &row); err != nil {
		fatal("parse input (expected {pricing, raw, diffs} JSON): %v", err)
	}

	var pe entity.PricingEvent
	if err := json.Unmarshal([]byte(row.Pricing), &pe); err != nil {
		fatal("parse pricing side: %v", err)
	}
	var raw entity.RawUserUnitCost
	if err := json.Unmarshal([]byte(row.Raw), &raw); err != nil {
		fatal("parse raw side: %v", err)
	}
	var diffs []billing.PricingFieldDiff
	if row.Diffs != "" {
		if err := json.Unmarshal([]byte(row.Diffs), &diffs); err != nil {
			fatal("parse diffs: %v", err)
		}
	}
	entries, err := pipeline.ParsePricingDetail(pe.PricingDetail)
	if err != nil {
		fatal("parse pricing detail: %v", err)
	}

	variant, trace := billing.ClassifyReplayArtifact(&pe, &raw, entries, diffs)
	if variant != "" {
		fmt.Printf("verdict: replay_artifact (variant=%s)\n", variant)
	} else {
		fmt.Println("verdict: mismatch (fingerprint failed closed — triage by hand)")
	}
	fmt.Printf("trace (cost_id=%s tenant=%d id=%d):\n", pe.CostID, pe.TenantID, row.ID)
	for _, line := range billing.ReplayTraceDetails(trace) {
		fmt.Printf("  %s\n", line)
	}
}

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