// radarjudgesample exports recent opportunities for human judge calibration (T535).
package main

import (
	"context"
	"encoding/csv"
	"flag"
	"fmt"
	"os"
	"time"

	"apps/backend/internal/config"
	"apps/backend/internal/module/radar/domain"
	"apps/backend/internal/module/radar/repository"

	"github.com/zeromicro/go-zero/core/conf"
)

func main() {
	f := flag.String("f", "etc/gateway.yaml", "config")
	owner := flag.Int64("owner", 0, "owner uid")
	out := flag.String("o", "judge-sample.csv", "output csv")
	flag.Parse()
	var c config.Config
	conf.MustLoad(*f, &c)
	c.ApplyEnv()
	repo := repository.NewMonStore(c.Mongo.URI, c.Mongo.Database)
	ctx := context.Background()
	list, _, err := repo.ListOpportunities(ctx, *owner, domain.OpportunityListFilter{Page: 1, PageSize: 100})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	w := csv.NewWriter(os.Stdout)
	if *out != "-" {
		fp, err := os.Create(*out)
		if err != nil {
			panic(err)
		}
		defer fp.Close()
		w = csv.NewWriter(fp)
	}
	_ = w.Write([]string{"id", "status", "intent_score", "intent_band", "region_match", "text", "human_label", "notes"})
	for _, o := range list {
		_ = w.Write([]string{o.ID, o.Status, fmt.Sprintf("%d", o.IntentScore), o.IntentBand, o.RegionMatch, trim(o.Text, 120), "", ""})
	}
	w.Flush()
	fmt.Fprintf(os.Stderr, "exported %d rows at %s\n", len(list), time.Now().UTC().Format(time.RFC3339))
}

func trim(s string, n int) string {
	r := []rune(s)
	if len(r) <= n {
		return s
	}
	return string(r[:n])
}
