package orchestrator_test

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/event"
	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/orchestrator"
	"github.com/flothus/tmux-xterm-research/server-go/internal/harness/store"
)

// TestPhaseH_OrgComparison is the Phase H done-criterion: two runs, two
// different orgs, comparable metrics produced and diffable.
func TestPhaseH_OrgComparison(t *testing.T) {
	tmp := t.TempDir()
	st, err := store.Open(filepath.Join(tmp, "harness.db"))
	if err != nil {
		t.Fatal(err)
	}
	defer st.Close()
	bus := event.NewBus(st)
	orch := orchestrator.New(st, bus)
	ctx := context.Background()

	// Run #1: hierarchical-v1, simulates 2 completed tasks, no thrash.
	_ = orch.CreateRun(ctx, "run-h-1", "")
	if err := orch.SetRunOrg(ctx, "run-h-1", "hierarchical-v1", 1, "roles/v1/"); err != nil {
		t.Fatal(err)
	}
	_, _ = st.DB().Exec(`INSERT INTO agents(id, run_id, status, spawned_at) VALUES('a1', 'run-h-1', 'running', ?)`, store.FmtTime(time.Now().UTC()))
	for _, id := range []string{"t1", "t2"} {
		_ = orch.CreateTask(ctx, orchestrator.Task{ID: id, RunID: "run-h-1", Title: id})
		_ = orch.AssignOwner(ctx, id, "a1")
		_ = orch.Transition(ctx, id, orchestrator.StateInProgress)
		_ = orch.Transition(ctx, id, orchestrator.StateCompleted)
	}
	_, _ = st.DB().Exec(`UPDATE runs SET tokens_total=10000, cost_usd_total=0.50 WHERE id='run-h-1'`)

	// Run #2: flat-swarm-v1, simulates 1 completed + 1 escalated, costs more.
	_ = orch.CreateRun(ctx, "run-h-2", "")
	if err := orch.SetRunOrg(ctx, "run-h-2", "flat-swarm-v1", 1, "roles/flat-v1/"); err != nil {
		t.Fatal(err)
	}
	_, _ = st.DB().Exec(`INSERT INTO agents(id, run_id, status, spawned_at) VALUES('b1', 'run-h-2', 'running', ?)`, store.FmtTime(time.Now().UTC()))
	_ = orch.CreateTask(ctx, orchestrator.Task{ID: "t3", RunID: "run-h-2", Title: "t3"})
	_ = orch.AssignOwner(ctx, "t3", "b1")
	_ = orch.Transition(ctx, "t3", orchestrator.StateInProgress)
	_ = orch.Transition(ctx, "t3", orchestrator.StateCompleted)
	_ = orch.CreateTask(ctx, orchestrator.Task{ID: "t4", RunID: "run-h-2", Title: "t4"})
	_ = orch.AssignOwner(ctx, "t4", "b1")
	_ = orch.Transition(ctx, "t4", orchestrator.StateInProgress)
	_ = orch.Transition(ctx, "t4", orchestrator.StateEscalated)
	_, _ = st.DB().Exec(`UPDATE runs SET tokens_total=25000, cost_usd_total=1.20 WHERE id='run-h-2'`)

	a, err := orch.LoadRunMetrics(ctx, "run-h-1")
	if err != nil {
		t.Fatal(err)
	}
	b, err := orch.LoadRunMetrics(ctx, "run-h-2")
	if err != nil {
		t.Fatal(err)
	}
	if a.OrgID != "hierarchical-v1" || b.OrgID != "flat-swarm-v1" {
		t.Errorf("org attribution: a=%s b=%s", a.OrgID, b.OrgID)
	}
	if a.TasksCompleted != 2 {
		t.Errorf("a.completed = %d, want 2", a.TasksCompleted)
	}
	if b.TasksCompleted != 1 || b.TasksEscalated != 1 {
		t.Errorf("b counts: completed=%d escalated=%d", b.TasksCompleted, b.TasksEscalated)
	}

	diff := orchestrator.CompareRuns(a, b)
	if diff["tokens_total"].Delta != 15000 {
		t.Errorf("tokens delta = %v, want 15000", diff["tokens_total"].Delta)
	}
	if diff["tasks_completed"].Delta != -1 {
		t.Errorf("completed delta = %v, want -1", diff["tasks_completed"].Delta)
	}
}
