package api

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/jackc/pgx/v5/pgtype"

	"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)

func date(s string) pgtype.Date {
	t, _ := time.Parse("2006-01-02", s)
	return pgtype.Date{Time: t, Valid: true}
}

func TestBuildTrendsResponse_SeriesMergingAndMarkers(t *testing.T) {
	src := func(s string) *string { return &s }
	now := time.Date(2026, 7, 3, 12, 0, 0, 0, time.UTC)
	rows := []dbq.RecommendationWeeklyTrendsRow{
		// Two radio session sources in the same week collapse into one
		// family point; completion weighting by sample count.
		{WeekStart: date("2026-06-22"), Source: src("radio:aaaa"),
			Plays: 3, Skips: 1, CompletionN: 3, AvgCompletion: 0.6, TasteHits: 3},
		{WeekStart: date("2026-06-22"), Source: src("radio:bbbb"),
			Plays: 1, Skips: 1, CompletionN: 1, AvgCompletion: 0.2, TasteHits: 0},
		{WeekStart: date("2026-06-29"), Source: src("radio:aaaa"),
			Plays: 2, Skips: 0, CompletionN: 2, AvgCompletion: 0.9, TasteHits: 1},
		// NULL source = manual baseline family.
		{WeekStart: date("2026-06-29"), Source: nil,
			Plays: 5, Skips: 1, CompletionN: 5, AvgCompletion: 0.8, TasteHits: 4},
	}
	audits := []dbq.RecommendationTuningAudit{
		{ID: 2, ChangedAt: pgtype.Timestamptz{Time: now.Add(-24 * time.Hour), Valid: true},
			Scope: "radio", Action: "update", Changes: []byte(`[{"field":"taste_weight","old":1,"new":2}]`)},
		// Older than the window → dropped.
		{ID: 1, ChangedAt: pgtype.Timestamptz{Time: now.Add(-100 * 7 * 24 * time.Hour), Valid: true},
			Scope: "taste", Action: "reset", Changes: []byte(`[]`)},
	}

	resp := buildTrendsResponse(12, now, rows, audits)

	if len(resp.Series) != 2 {
		t.Fatalf("series = %d, want 2 (radio + manual)", len(resp.Series))
	}
	radio := resp.Series[0] // 6 plays > manual's 5 → sorted first
	if radio.Key != "radio" || radio.Plays != 6 {
		t.Fatalf("series[0] = %s/%d, want radio/6", radio.Key, radio.Plays)
	}
	if len(radio.Points) != 2 {
		t.Fatalf("radio points = %d, want 2 weeks", len(radio.Points))
	}
	wk1 := radio.Points[0]
	if wk1.WeekStart != "2026-06-22" || wk1.Plays != 4 || wk1.Skips != 2 {
		t.Errorf("week1 = %+v, want 2026-06-22 with 4 plays / 2 skips", wk1)
	}
	if wk1.SkipRate != 0.5 {
		t.Errorf("week1 skip_rate = %v, want 0.5", wk1.SkipRate)
	}
	// Completion weighted by sample count: (0.6*3 + 0.2*1) / 4 = 0.5.
	if wk1.AvgCompletion < 0.49 || wk1.AvgCompletion > 0.51 {
		t.Errorf("week1 avg_completion = %v, want 0.5", wk1.AvgCompletion)
	}
	// Taste hits: 3 of 4 plays.
	if wk1.TasteHitRate != 0.75 {
		t.Errorf("week1 taste_hit_rate = %v, want 0.75", wk1.TasteHitRate)
	}
	if manual := resp.Series[1]; manual.Key != "manual" || manual.Intent != "" {
		t.Errorf("series[1] = %+v, want the manual baseline family", manual)
	}

	if len(resp.Markers) != 1 {
		t.Fatalf("markers = %d, want 1 (out-of-window marker dropped)", len(resp.Markers))
	}
	if resp.Markers[0].Scope != "radio" || resp.Markers[0].Action != "update" {
		t.Errorf("marker = %+v, want radio/update", resp.Markers[0])
	}
}

func newTrendsRouter(h *handlers) chi.Router {
	r := chi.NewRouter()
	r.Get("/api/admin/recommendation-trends", h.handleGetRecommendationTrends)
	return r
}

func TestRecommendationTrends_EndToEnd(t *testing.T) {
	h, pool := testHandlers(t)
	user := seedUser(t, pool, "trends", "pw", true)
	artist := seedArtist(t, pool, "TrendArtist")
	album := seedAlbum(t, pool, artist.ID, "TrendAlbum", 2020)
	tk := seedTrack(t, pool, album.ID, artist.ID, "TrendTrack", 1, 200000)
	session := seedPlaySession(t, pool, user.ID, time.Now())

	// Positive taste weight for the artist → plays count as taste hits.
	if _, err := pool.Exec(context.Background(),
		`INSERT INTO taste_profile_artists (user_id, artist_id, weight) VALUES ($1, $2, 1.5)`,
		user.ID, artist.ID); err != nil {
		t.Fatalf("seed taste profile: %v", err)
	}
	radio := "radio"
	seedSourcedPlay(t, h, user.ID, tk.ID, session, &radio, nil, 0.9, false)
	// A knob turn to mark the timeline.
	if err := h.recSettings.UpdateProfile(context.Background(), "radio",
		map[string]float64{"taste_weight": 2}); err != nil {
		t.Fatalf("UpdateProfile: %v", err)
	}

	req := httptest.NewRequest(http.MethodGet, "/api/admin/recommendation-trends", nil)
	rec := httptest.NewRecorder()
	newTrendsRouter(h).ServeHTTP(rec, req)
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200 (%s)", rec.Code, rec.Body.String())
	}
	var resp trendsResp
	if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if resp.Weeks != trendsDefaultWeeks {
		t.Errorf("weeks = %d, want %d", resp.Weeks, trendsDefaultWeeks)
	}
	var radioSeries *trendSeries
	for i := range resp.Series {
		if resp.Series[i].Key == "radio" {
			radioSeries = &resp.Series[i]
		}
	}
	if radioSeries == nil || len(radioSeries.Points) != 1 {
		t.Fatalf("radio series = %+v, want one point", radioSeries)
	}
	if radioSeries.Points[0].TasteHitRate != 1.0 {
		t.Errorf("taste_hit_rate = %v, want 1.0 (positive-weight artist)",
			radioSeries.Points[0].TasteHitRate)
	}
	if len(resp.Markers) != 1 || resp.Markers[0].Scope != "radio" {
		t.Errorf("markers = %+v, want the radio knob turn", resp.Markers)
	}
}

func TestRecommendationTrends_InvalidWeeks(t *testing.T) {
	h, _ := testHandlers(t)
	req := httptest.NewRequest(http.MethodGet, "/api/admin/recommendation-trends?weeks=zero", nil)
	rec := httptest.NewRecorder()
	newTrendsRouter(h).ServeHTTP(rec, req)
	if rec.Code != http.StatusBadRequest {
		t.Errorf("status = %d, want 400", rec.Code)
	}
}
