// materializer — Go-side build_evidence_index runner. Reads source
// JSONL streams in `data/_kb/`, transforms each row to an
// EvidenceRecord, writes day-partitioned output under `data/evidence/`
// + an audit-grade receipt under `reports/distillation/<ts>/`.
//
// Mirrors the Bun runner at scripts/distillation/build_evidence_index.ts
// — both runtimes can run against the same root and produce
// interoperable outputs (per ADR-001 #4: same logic, on-wire
// JSON shape preserved).
//
// Usage:
//
//	materializer                                        # full run, write outputs
//	materializer -dry-run                               # count, no writes
//	materializer -root /home/profit/lakehouse           # custom repo root
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"time"

	"git.agentview.dev/profit/golangLAKEHOUSE/internal/materializer"
)

func main() {
	root := flag.String("root", defaultRoot(), "lakehouse repo root (defaults to $LH_DISTILL_ROOT or current dir)")
	dryRun := flag.Bool("dry-run", false, "count rows but do not write outputs")
	flag.Parse()

	recordedAt := time.Now().UTC().Format(time.RFC3339Nano)

	res, err := materializer.MaterializeAll(materializer.MaterializeOptions{
		Root:       *root,
		Transforms: materializer.Transforms,
		RecordedAt: recordedAt,
		DryRun:     *dryRun,
	})
	if err != nil {
		log.Fatalf("materializer: %v", err)
	}

	suffix := ""
	if *dryRun {
		suffix = " (DRY RUN)"
	}
	fmt.Printf("[evidence_index] %d read · %d written · %d skipped · %d deduped%s\n",
		res.Totals.RowsRead, res.Totals.RowsWritten, res.Totals.RowsSkipped, res.Totals.RowsDeduped, suffix)
	for _, s := range res.Sources {
		if !s.RowsPresent {
			fmt.Printf("  %s: (missing — skipped)\n", s.SourceFileRelPath)
			continue
		}
		fmt.Printf("  %s: read=%d wrote=%d skip=%d dedup=%d\n",
			s.SourceFileRelPath, s.RowsRead, s.RowsWritten, s.RowsSkipped, s.RowsDeduped)
	}

	if !*dryRun {
		fmt.Printf("[evidence_index] receipt: %s\n", res.ReceiptPath)
		fmt.Printf("[evidence_index] validation_pass=%v\n", res.Receipt.ValidationPass)
	}

	if !res.Receipt.ValidationPass {
		os.Exit(1)
	}
}

func defaultRoot() string {
	if r := os.Getenv("LH_DISTILL_ROOT"); r != "" {
		return r
	}
	if cwd, err := os.Getwd(); err == nil {
		return cwd
	}
	return "."
}
