// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.31.1
// source: recommendation.sql

package dbq

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const listLastPlayedArtistsForUser = `-- name: ListLastPlayedArtistsForUser :many
SELECT a.id, a.name, a.sort_name, a.mbid, a.created_at, a.updated_at,
       cov.id        AS cover_album_id,
       cnt.album_count::bigint AS album_count,
       max_started.started_at::timestamptz AS last_played_at
FROM artists a
JOIN LATERAL (
    SELECT max(pe.started_at) AS started_at
    FROM play_events pe
    JOIN tracks t ON t.id = pe.track_id
    WHERE pe.user_id = $1 AND t.artist_id = a.id
) max_started ON max_started.started_at IS NOT NULL
LEFT JOIN LATERAL (
    SELECT id FROM albums
    WHERE artist_id = a.id AND cover_art_path IS NOT NULL
    ORDER BY created_at DESC LIMIT 1
) cov ON true
LEFT JOIN LATERAL (
    SELECT count(*) AS album_count
    FROM albums WHERE artist_id = a.id
) cnt ON true
ORDER BY max_started.started_at DESC, a.id
LIMIT $2
`

type ListLastPlayedArtistsForUserParams struct {
	UserID pgtype.UUID
	Limit  int32
}

type ListLastPlayedArtistsForUserRow struct {
	Artist       Artist
	CoverAlbumID pgtype.UUID
	AlbumCount   int64
	LastPlayedAt pgtype.Timestamptz
}

// M6a: artists ranked by max(play_events.started_at) for the user, with
// a derived cover_album_id via a representative-album lateral join (most
// recent album that has cover_art_path set). album_count joined for the
// ArtistRef wire shape.
func (q *Queries) ListLastPlayedArtistsForUser(ctx context.Context, arg ListLastPlayedArtistsForUserParams) ([]ListLastPlayedArtistsForUserRow, error) {
	rows, err := q.db.Query(ctx, listLastPlayedArtistsForUser, arg.UserID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListLastPlayedArtistsForUserRow
	for rows.Next() {
		var i ListLastPlayedArtistsForUserRow
		if err := rows.Scan(
			&i.Artist.ID,
			&i.Artist.Name,
			&i.Artist.SortName,
			&i.Artist.Mbid,
			&i.Artist.CreatedAt,
			&i.Artist.UpdatedAt,
			&i.CoverAlbumID,
			&i.AlbumCount,
			&i.LastPlayedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listMostPlayedTracksForUser = `-- name: ListMostPlayedTracksForUser :many
SELECT t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at,
       albums.title AS album_title,
       artists.name AS artist_name
FROM tracks t
JOIN albums  ON albums.id  = t.album_id
JOIN artists ON artists.id = t.artist_id
JOIN play_events pe ON pe.track_id = t.id
WHERE pe.user_id = $1
  AND pe.was_skipped = false
  AND NOT EXISTS (
      SELECT 1 FROM lidarr_quarantine q
      WHERE q.user_id = $1 AND q.track_id = t.id
  )
GROUP BY t.id, t.title, t.album_id, t.artist_id, t.duration_ms, t.file_path,
         t.file_format, t.file_size, t.bitrate, t.track_number, t.disc_number,
         t.mbid, t.genre, t.added_at, t.updated_at,
         albums.title, artists.name
ORDER BY count(*) DESC, t.id
LIMIT $2
`

type ListMostPlayedTracksForUserParams struct {
	UserID pgtype.UUID
	Limit  int32
}

type ListMostPlayedTracksForUserRow struct {
	Track      Track
	AlbumTitle string
	ArtistName string
}

// M6a: top-N tracks by completed-play count for the user. was_skipped
// excludes skips so a user spamming next doesn't fabricate a top track.
// Quarantined tracks (per-user soft-hide from M5b) are filtered out.
func (q *Queries) ListMostPlayedTracksForUser(ctx context.Context, arg ListMostPlayedTracksForUserParams) ([]ListMostPlayedTracksForUserRow, error) {
	rows, err := q.db.Query(ctx, listMostPlayedTracksForUser, arg.UserID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListMostPlayedTracksForUserRow
	for rows.Next() {
		var i ListMostPlayedTracksForUserRow
		if err := rows.Scan(
			&i.Track.ID,
			&i.Track.Title,
			&i.Track.AlbumID,
			&i.Track.ArtistID,
			&i.Track.TrackNumber,
			&i.Track.DiscNumber,
			&i.Track.DurationMs,
			&i.Track.FilePath,
			&i.Track.FileSize,
			&i.Track.FileFormat,
			&i.Track.Bitrate,
			&i.Track.Mbid,
			&i.Track.Genre,
			&i.Track.AddedAt,
			&i.Track.UpdatedAt,
			&i.AlbumTitle,
			&i.ArtistName,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRediscoverAlbumsFallbackForUser = `-- name: ListRediscoverAlbumsFallbackForUser :many
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, artists.name AS artist_name
FROM general_likes_albums gla
JOIN albums  ON albums.id = gla.album_id
JOIN artists ON artists.id = albums.artist_id
WHERE gla.user_id = $1
ORDER BY random()
LIMIT $2
`

type ListRediscoverAlbumsFallbackForUserParams struct {
	UserID pgtype.UUID
	Limit  int32
}

type ListRediscoverAlbumsFallbackForUserRow struct {
	Album      Album
	ArtistName string
}

// M6a: random sample of liked albums for the user. The Go service uses
// this to top up the rediscover row when ListRediscoverAlbumsForUser
// returns fewer than `limit` rows.
func (q *Queries) ListRediscoverAlbumsFallbackForUser(ctx context.Context, arg ListRediscoverAlbumsFallbackForUserParams) ([]ListRediscoverAlbumsFallbackForUserRow, error) {
	rows, err := q.db.Query(ctx, listRediscoverAlbumsFallbackForUser, arg.UserID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListRediscoverAlbumsFallbackForUserRow
	for rows.Next() {
		var i ListRediscoverAlbumsFallbackForUserRow
		if err := rows.Scan(
			&i.Album.ID,
			&i.Album.Title,
			&i.Album.SortTitle,
			&i.Album.ArtistID,
			&i.Album.ReleaseDate,
			&i.Album.Mbid,
			&i.Album.CoverArtPath,
			&i.Album.CreatedAt,
			&i.Album.UpdatedAt,
			&i.ArtistName,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRediscoverAlbumsForUser = `-- name: ListRediscoverAlbumsForUser :many
WITH eligible AS (
    SELECT al.id        AS album_id,
           gla.liked_at,
           max(pe.started_at) AS last_played
    FROM general_likes_albums gla
    JOIN albums al ON al.id = gla.album_id
    LEFT JOIN tracks t       ON t.album_id = al.id
    LEFT JOIN play_events pe ON pe.track_id = t.id AND pe.user_id = $1
    WHERE gla.user_id = $1
      AND gla.liked_at < now() - interval '30 days'
    GROUP BY al.id, gla.liked_at
    HAVING COALESCE(max(pe.started_at), '1970-01-01'::timestamptz)
           < now() - interval '14 days'
)
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, artists.name AS artist_name
FROM eligible e
JOIN albums  ON albums.id = e.album_id
JOIN artists ON artists.id = albums.artist_id
ORDER BY (now() - COALESCE(e.last_played, e.liked_at)) DESC, albums.id
LIMIT $2
`

type ListRediscoverAlbumsForUserParams struct {
	UserID pgtype.UUID
	Limit  int32
}

type ListRediscoverAlbumsForUserRow struct {
	Album      Album
	ArtistName string
}

// M6a: albums liked >30 days ago AND not played in the last 14 days,
// ordered by longest-since-last-play first. The HAVING clause uses an
// epoch sentinel so albums with NO plays count as eligible (their
// "last play" is treated as 1970, which is always >14 days ago).
func (q *Queries) ListRediscoverAlbumsForUser(ctx context.Context, arg ListRediscoverAlbumsForUserParams) ([]ListRediscoverAlbumsForUserRow, error) {
	rows, err := q.db.Query(ctx, listRediscoverAlbumsForUser, arg.UserID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListRediscoverAlbumsForUserRow
	for rows.Next() {
		var i ListRediscoverAlbumsForUserRow
		if err := rows.Scan(
			&i.Album.ID,
			&i.Album.Title,
			&i.Album.SortTitle,
			&i.Album.ArtistID,
			&i.Album.ReleaseDate,
			&i.Album.Mbid,
			&i.Album.CoverArtPath,
			&i.Album.CreatedAt,
			&i.Album.UpdatedAt,
			&i.ArtistName,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRediscoverArtistsFallbackForUser = `-- name: ListRediscoverArtistsFallbackForUser :many
SELECT artists.id, artists.name, artists.sort_name, artists.mbid, artists.created_at, artists.updated_at,
       cov.id AS cover_album_id,
       cnt.album_count::bigint AS album_count
FROM general_likes_artists gla
JOIN artists ON artists.id = gla.artist_id
LEFT JOIN LATERAL (
    SELECT id FROM albums
    WHERE artist_id = artists.id AND cover_art_path IS NOT NULL
    ORDER BY created_at DESC LIMIT 1
) cov ON true
LEFT JOIN LATERAL (
    SELECT count(*) AS album_count
    FROM albums WHERE artist_id = artists.id
) cnt ON true
WHERE gla.user_id = $1
ORDER BY random()
LIMIT $2
`

type ListRediscoverArtistsFallbackForUserParams struct {
	UserID pgtype.UUID
	Limit  int32
}

type ListRediscoverArtistsFallbackForUserRow struct {
	Artist       Artist
	CoverAlbumID pgtype.UUID
	AlbumCount   int64
}

func (q *Queries) ListRediscoverArtistsFallbackForUser(ctx context.Context, arg ListRediscoverArtistsFallbackForUserParams) ([]ListRediscoverArtistsFallbackForUserRow, error) {
	rows, err := q.db.Query(ctx, listRediscoverArtistsFallbackForUser, arg.UserID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListRediscoverArtistsFallbackForUserRow
	for rows.Next() {
		var i ListRediscoverArtistsFallbackForUserRow
		if err := rows.Scan(
			&i.Artist.ID,
			&i.Artist.Name,
			&i.Artist.SortName,
			&i.Artist.Mbid,
			&i.Artist.CreatedAt,
			&i.Artist.UpdatedAt,
			&i.CoverAlbumID,
			&i.AlbumCount,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listRediscoverArtistsForUser = `-- name: ListRediscoverArtistsForUser :many
WITH eligible AS (
    SELECT a.id        AS artist_id,
           gla.liked_at,
           max(pe.started_at) AS last_played
    FROM general_likes_artists gla
    JOIN artists a ON a.id = gla.artist_id
    LEFT JOIN tracks t       ON t.artist_id = a.id
    LEFT JOIN play_events pe ON pe.track_id = t.id AND pe.user_id = $1
    WHERE gla.user_id = $1
      AND gla.liked_at < now() - interval '30 days'
    GROUP BY a.id, gla.liked_at
    HAVING COALESCE(max(pe.started_at), '1970-01-01'::timestamptz)
           < now() - interval '14 days'
)
SELECT artists.id, artists.name, artists.sort_name, artists.mbid, artists.created_at, artists.updated_at,
       cov.id AS cover_album_id,
       cnt.album_count::bigint AS album_count
FROM eligible e
JOIN artists ON artists.id = e.artist_id
LEFT JOIN LATERAL (
    SELECT id FROM albums
    WHERE artist_id = artists.id AND cover_art_path IS NOT NULL
    ORDER BY created_at DESC LIMIT 1
) cov ON true
LEFT JOIN LATERAL (
    SELECT count(*) AS album_count
    FROM albums WHERE artist_id = artists.id
) cnt ON true
ORDER BY (now() - COALESCE(e.last_played, e.liked_at)) DESC, artists.id
LIMIT $2
`

type ListRediscoverArtistsForUserParams struct {
	UserID pgtype.UUID
	Limit  int32
}

type ListRediscoverArtistsForUserRow struct {
	Artist       Artist
	CoverAlbumID pgtype.UUID
	AlbumCount   int64
}

// M6a: artists liked >30 days ago AND none of their tracks played in the
// last 14 days, ordered by longest-since-last-play. cover_album_id is
// derived from a representative album (LEFT JOIN LATERAL).
func (q *Queries) ListRediscoverArtistsForUser(ctx context.Context, arg ListRediscoverArtistsForUserParams) ([]ListRediscoverArtistsForUserRow, error) {
	rows, err := q.db.Query(ctx, listRediscoverArtistsForUser, arg.UserID, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []ListRediscoverArtistsForUserRow
	for rows.Next() {
		var i ListRediscoverArtistsForUserRow
		if err := rows.Scan(
			&i.Artist.ID,
			&i.Artist.Name,
			&i.Artist.SortName,
			&i.Artist.Mbid,
			&i.Artist.CreatedAt,
			&i.Artist.UpdatedAt,
			&i.CoverAlbumID,
			&i.AlbumCount,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const loadRadioCandidates = `-- name: LoadRadioCandidates :many
SELECT
    t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at,
    (l.user_id IS NOT NULL)::bool AS is_liked,
    pe.last_played_at::timestamptz AS last_played_at,
    pe.play_count,
    pe.skip_count
FROM tracks t
LEFT JOIN general_likes l ON l.user_id = $1 AND l.track_id = t.id
LEFT JOIN LATERAL (
    SELECT
        max(started_at) AS last_played_at,
        count(*) AS play_count,
        count(*) FILTER (WHERE was_skipped) AS skip_count
    FROM play_events
    WHERE user_id = $1 AND track_id = t.id
) pe ON true
WHERE t.id <> $2
  AND NOT EXISTS (
    SELECT 1 FROM play_events
    WHERE user_id = $1 AND track_id = t.id
      AND started_at > now() - $3 * interval '1 hour'
  )
  AND NOT EXISTS (
    SELECT 1 FROM lidarr_quarantine q
    WHERE q.user_id = $1 AND q.track_id = t.id
  )
`

type LoadRadioCandidatesParams struct {
	UserID  pgtype.UUID
	ID      pgtype.UUID
	Column3 interface{}
}

type LoadRadioCandidatesRow struct {
	Track        Track
	IsLiked      bool
	LastPlayedAt pgtype.Timestamptz
	PlayCount    int64
	SkipCount    int64
}

// Returns all tracks except the seed and any played by the user within
// the last $3 hours, joined with the stats needed for scoring:
//
//	is_liked     — boolean from general_likes for this user
//	last_played_at — max(play_events.started_at) for this user/track
//	play_count   — count of play_events for this user/track
//	skip_count   — play_events where was_skipped=true
func (q *Queries) LoadRadioCandidates(ctx context.Context, arg LoadRadioCandidatesParams) ([]LoadRadioCandidatesRow, error) {
	rows, err := q.db.Query(ctx, loadRadioCandidates, arg.UserID, arg.ID, arg.Column3)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []LoadRadioCandidatesRow
	for rows.Next() {
		var i LoadRadioCandidatesRow
		if err := rows.Scan(
			&i.Track.ID,
			&i.Track.Title,
			&i.Track.AlbumID,
			&i.Track.ArtistID,
			&i.Track.TrackNumber,
			&i.Track.DiscNumber,
			&i.Track.DurationMs,
			&i.Track.FilePath,
			&i.Track.FileSize,
			&i.Track.FileFormat,
			&i.Track.Bitrate,
			&i.Track.Mbid,
			&i.Track.Genre,
			&i.Track.AddedAt,
			&i.Track.UpdatedAt,
			&i.IsLiked,
			&i.LastPlayedAt,
			&i.PlayCount,
			&i.SkipCount,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const loadRadioCandidatesV2 = `-- name: LoadRadioCandidatesV2 :many

WITH
seed_artist AS (
    SELECT artist_id
    FROM tracks
    WHERE tracks.id = $2
),
seed_tags AS (
    SELECT trim(g) AS tag
    FROM tracks t
    LEFT JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g(tag) ON true
    WHERE t.id = $2 AND trim(g) <> ''
),
excluded_ids AS (
    SELECT unnest($4::uuid[]) AS id
    UNION ALL
    SELECT pe.track_id AS id
    FROM play_events pe
    WHERE pe.user_id = $1 AND pe.started_at > now() - $3 * interval '1 hour'
    UNION ALL
    SELECT q.track_id AS id
    FROM lidarr_quarantine q
    WHERE q.user_id = $1
),
lb_similar AS (
    SELECT ts.track_b_id AS track_id, ts.score AS sim_score
    FROM track_similarity ts
    WHERE ts.track_a_id = $2
      AND ts.source = 'listenbrainz'
      AND ts.track_b_id NOT IN (SELECT id FROM excluded_ids)
    ORDER BY ts.score DESC
    LIMIT $5
),
similar_artists AS (
    SELECT t.id AS track_id, asim.score * 0.5 AS sim_score
    FROM artist_similarity asim
    JOIN tracks t ON t.artist_id = asim.artist_b_id
    JOIN seed_artist sa ON asim.artist_a_id = sa.artist_id
    WHERE asim.source = 'listenbrainz'
      AND t.id NOT IN (SELECT id FROM excluded_ids)
    ORDER BY asim.score DESC, random()
    LIMIT $6
),
tag_overlap AS (
    SELECT t.id AS track_id,
           (count(DISTINCT trim(g))::float8
            / GREATEST((SELECT count(*) FROM seed_tags), 1)) AS sim_score
    FROM tracks t
    LEFT JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g_split(g) ON true
    WHERE trim(g_split.g) IN (SELECT tag FROM seed_tags)
      AND t.id NOT IN (SELECT id FROM excluded_ids)
      AND t.id <> $2
    GROUP BY t.id
    HAVING count(DISTINCT trim(g_split.g)) > 0
    ORDER BY sim_score DESC
    LIMIT $7
),
likes_overlap AS (
    SELECT gl.track_id, 0.6::float8 AS sim_score
    FROM general_likes gl
    WHERE gl.user_id = $1
      AND gl.track_id NOT IN (SELECT id FROM excluded_ids)
      AND EXISTS (
          SELECT 1 FROM tracks t
          LEFT JOIN LATERAL regexp_split_to_table(coalesce(t.genre, ''), '[;,]') AS g_overlap(g) ON true
          WHERE t.id = gl.track_id
            AND trim(g_overlap.g) IN (SELECT tag FROM seed_tags)
      )
    ORDER BY random()
    LIMIT $8
),
random_fill AS (
    SELECT t.id AS track_id, 0.0::float8 AS sim_score
    FROM tracks t
    WHERE t.id NOT IN (SELECT id FROM excluded_ids)
      AND t.id <> $2
      AND t.id NOT IN (
          SELECT track_id FROM lb_similar
          UNION SELECT track_id FROM similar_artists
          UNION SELECT track_id FROM tag_overlap
          UNION SELECT track_id FROM likes_overlap
      )
    ORDER BY random()
    LIMIT $9
)
SELECT
    t.id, t.title, t.album_id, t.artist_id, t.track_number, t.disc_number, t.duration_ms, t.file_path, t.file_size, t.file_format, t.bitrate, t.mbid, t.genre, t.added_at, t.updated_at,
    (l.user_id IS NOT NULL)::bool AS is_liked,
    pe.last_played_at::timestamptz AS last_played_at,
    pe.play_count,
    pe.skip_count,
    COALESCE(max(u.sim_score), 0.0) AS similarity_score
FROM (
    SELECT track_id, sim_score FROM lb_similar
    UNION ALL SELECT track_id, sim_score FROM similar_artists
    UNION ALL SELECT track_id, sim_score FROM tag_overlap
    UNION ALL SELECT track_id, sim_score FROM likes_overlap
    UNION ALL SELECT track_id, sim_score FROM random_fill
) u
JOIN tracks t ON t.id = u.track_id
LEFT JOIN general_likes l ON l.user_id = $1 AND l.track_id = t.id
LEFT JOIN LATERAL (
    SELECT max(started_at) AS last_played_at,
           count(*) AS play_count,
           count(*) FILTER (WHERE was_skipped) AS skip_count
    FROM play_events
    WHERE user_id = $1 AND track_id = t.id
) pe ON true
GROUP BY t.id, t.title, t.album_id, t.artist_id, t.duration_ms, t.file_path,
         t.file_format, t.file_size, t.bitrate, t.track_number, t.disc_number,
         t.mbid, t.genre, t.added_at, t.updated_at,
         l.user_id, pe.last_played_at, pe.play_count, pe.skip_count
`

type LoadRadioCandidatesV2Params struct {
	UserID  pgtype.UUID
	ID      pgtype.UUID
	Column3 interface{}
	Column4 []pgtype.UUID
	Limit   int32
	Limit_2 int32
	Limit_3 int32
	Limit_4 int32
	Limit_5 int32
}

type LoadRadioCandidatesV2Row struct {
	Track           Track
	IsLiked         bool
	LastPlayedAt    pgtype.Timestamptz
	PlayCount       int64
	SkipCount       int64
	SimilarityScore interface{}
}

// M4c: similarity-driven candidate pool. 5-way UNION:
//
//	$1 user_id, $2 seed_track_id, $3 recently_played_hours,
//	$4 exclude (uuid[]), $5 lb_similar K, $6 similar_artists K,
//	$7 tag_overlap K, $8 likes_overlap K, $9 random_fill K.
//
// Returns same shape as LoadRadioCandidates plus similarity_score column.
func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandidatesV2Params) ([]LoadRadioCandidatesV2Row, error) {
	rows, err := q.db.Query(ctx, loadRadioCandidatesV2,
		arg.UserID,
		arg.ID,
		arg.Column3,
		arg.Column4,
		arg.Limit,
		arg.Limit_2,
		arg.Limit_3,
		arg.Limit_4,
		arg.Limit_5,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []LoadRadioCandidatesV2Row
	for rows.Next() {
		var i LoadRadioCandidatesV2Row
		if err := rows.Scan(
			&i.Track.ID,
			&i.Track.Title,
			&i.Track.AlbumID,
			&i.Track.ArtistID,
			&i.Track.TrackNumber,
			&i.Track.DiscNumber,
			&i.Track.DurationMs,
			&i.Track.FilePath,
			&i.Track.FileSize,
			&i.Track.FileFormat,
			&i.Track.Bitrate,
			&i.Track.Mbid,
			&i.Track.Genre,
			&i.Track.AddedAt,
			&i.Track.UpdatedAt,
			&i.IsLiked,
			&i.LastPlayedAt,
			&i.PlayCount,
			&i.SkipCount,
			&i.SimilarityScore,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const suggestArtistsForUser = `-- name: SuggestArtistsForUser :many
WITH seeds AS (
    SELECT a.id AS artist_id,
           5.0 * (CASE WHEN gla.artist_id IS NOT NULL THEN 1 ELSE 0 END)
           + COALESCE(SUM(EXP(- EXTRACT(epoch FROM now() - pe.started_at) / ($2::float8 * 86400.0))), 0)
           AS signal,
           (gla.artist_id IS NOT NULL) AS is_liked,
           COUNT(pe.id)::bigint AS play_count
    FROM artists a
    LEFT JOIN general_likes_artists gla ON gla.artist_id = a.id AND gla.user_id = $1
    LEFT JOIN tracks t ON t.artist_id = a.id
    LEFT JOIN play_events pe ON pe.track_id = t.id AND pe.user_id = $1
    WHERE gla.artist_id IS NOT NULL OR pe.id IS NOT NULL
    GROUP BY a.id, gla.artist_id
),
contributions AS (
    SELECT u.candidate_mbid,
           u.candidate_name,
           seeds.artist_id AS seed_id,
           seeds.is_liked,
           seeds.play_count,
           seeds.signal * u.score AS contribution
    FROM artist_similarity_unmatched u
    JOIN seeds ON seeds.artist_id = u.seed_artist_id
    WHERE NOT EXISTS (SELECT 1 FROM artists WHERE mbid = u.candidate_mbid)
      AND NOT EXISTS (
          SELECT 1 FROM lidarr_requests r
           WHERE r.user_id = $1
             AND r.lidarr_artist_mbid = u.candidate_mbid
             AND r.status NOT IN ('rejected', 'failed')
      )
)
SELECT candidate_mbid,
       candidate_name,
       SUM(contribution)::float8 AS total_score,
       ((array_agg(seed_id      ORDER BY contribution DESC))[1:3])::uuid[]    AS top_seed_ids,
       ((array_agg(contribution ORDER BY contribution DESC))[1:3])::float8[]  AS top_contributions,
       ((array_agg(is_liked     ORDER BY contribution DESC))[1:3])::boolean[] AS top_is_liked,
       ((array_agg(play_count   ORDER BY contribution DESC))[1:3])::bigint[]  AS top_play_counts
FROM contributions
GROUP BY candidate_mbid, candidate_name
ORDER BY total_score DESC
LIMIT $3
`

type SuggestArtistsForUserParams struct {
	UserID  pgtype.UUID
	Column2 float64
	Limit   int32
}

type SuggestArtistsForUserRow struct {
	CandidateMbid    string
	CandidateName    string
	TotalScore       float64
	TopSeedIds       []pgtype.UUID
	TopContributions []float64
	TopIsLiked       []bool
	TopPlayCounts    []int64
}

// M5c: per-user artist suggestions ranked by signal x similarity. The
// seeds CTE collects the user's likes (x5) plus recency-decayed plays
// (exp(-age_days / $2)). The contributions CTE joins those seeds against
// artist_similarity_unmatched and filters out candidates already in
// library or already in a non-terminal lidarr_request. The outer SELECT
// aggregates per candidate, returning the top-3 contributing seeds for
// attribution. $1=user_id, $2=half_life_days, $3=limit.
func (q *Queries) SuggestArtistsForUser(ctx context.Context, arg SuggestArtistsForUserParams) ([]SuggestArtistsForUserRow, error) {
	rows, err := q.db.Query(ctx, suggestArtistsForUser, arg.UserID, arg.Column2, arg.Limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []SuggestArtistsForUserRow
	for rows.Next() {
		var i SuggestArtistsForUserRow
		if err := rows.Scan(
			&i.CandidateMbid,
			&i.CandidateName,
			&i.TotalScore,
			&i.TopSeedIds,
			&i.TopContributions,
			&i.TopIsLiked,
			&i.TopPlayCounts,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}
