Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

116 KB
Raw Blame
// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.29.0
// source: voice_media.sql

package store

import (
	"context"

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

const activateVoiceMediaEpoch = `-- name: ActivateVoiceMediaEpoch :one
UPDATE voice_media_epochs
SET provider_egress_id=$2,observed_state='active',first_archived_ms=$3,
    archived_through_ms=$3,last_failure_code=NULL,updated_at=clock_timestamp()
WHERE id=$1 AND observed_state IN ('requested','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type ActivateVoiceMediaEpochParams struct {
	ID               string      `json:"id"`
	ProviderEgressID pgtype.Text `json:"provider_egress_id"`
	FirstArchivedMs  pgtype.Int8 `json:"first_archived_ms"`
}

func (q *Queries) ActivateVoiceMediaEpoch(ctx context.Context, arg ActivateVoiceMediaEpochParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, activateVoiceMediaEpoch, arg.ID, arg.ProviderEgressID, arg.FirstArchivedMs)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const activateVoiceSession = `-- name: ActivateVoiceSession :one
UPDATE voice_sessions
SET status='connected',last_failure_code=NULL,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','reconnecting')
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

func (q *Queries) ActivateVoiceSession(ctx context.Context, id string) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, activateVoiceSession, id)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const advanceVoiceMediaEpochObservation = `-- name: AdvanceVoiceMediaEpochObservation :one
UPDATE voice_media_epochs
SET provider_egress_id=coalesce(provider_egress_id,$2),observed_state=$3,
    archived_through_ms=greatest(coalesce(archived_through_ms,0),$4),
    last_failure_code=NULL,updated_at=clock_timestamp()
WHERE id=$1 AND observed_state IN ('requested','active','sealing','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type AdvanceVoiceMediaEpochObservationParams struct {
	ID                string      `json:"id"`
	ProviderEgressID  pgtype.Text `json:"provider_egress_id"`
	ObservedState     string      `json:"observed_state"`
	ArchivedThroughMs pgtype.Int8 `json:"archived_through_ms"`
}

func (q *Queries) AdvanceVoiceMediaEpochObservation(ctx context.Context, arg AdvanceVoiceMediaEpochObservationParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, advanceVoiceMediaEpochObservation,
		arg.ID,
		arg.ProviderEgressID,
		arg.ObservedState,
		arg.ArchivedThroughMs,
	)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const advanceVoiceSessionCredentialGeneration = `-- name: AdvanceVoiceSessionCredentialGeneration :one
UPDATE voice_sessions
SET credential_generation=credential_generation+1,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting')
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

func (q *Queries) AdvanceVoiceSessionCredentialGeneration(ctx context.Context, id string) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, advanceVoiceSessionCredentialGeneration, id)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const attachCaptureMediaOutputDocument = `-- name: AttachCaptureMediaOutputDocument :one
UPDATE capture_media_outputs
SET document_id=$2,document_version_id=$3
WHERE id=$1 AND document_id IS NULL AND document_version_id IS NULL
RETURNING id, capture_session_id, purpose, range_digest, object_key, filename, media_type, duration_ms, size_bytes, sha256, document_id, document_version_id, created_at
`

type AttachCaptureMediaOutputDocumentParams struct {
	ID                string      `json:"id"`
	DocumentID        pgtype.Text `json:"document_id"`
	DocumentVersionID pgtype.Text `json:"document_version_id"`
}

func (q *Queries) AttachCaptureMediaOutputDocument(ctx context.Context, arg AttachCaptureMediaOutputDocumentParams) (CaptureMediaOutput, error) {
	row := q.db.QueryRow(ctx, attachCaptureMediaOutputDocument, arg.ID, arg.DocumentID, arg.DocumentVersionID)
	var i CaptureMediaOutput
	err := row.Scan(
		&i.ID,
		&i.CaptureSessionID,
		&i.Purpose,
		&i.RangeDigest,
		&i.ObjectKey,
		&i.Filename,
		&i.MediaType,
		&i.DurationMs,
		&i.SizeBytes,
		&i.Sha256,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.CreatedAt,
	)
	return i, err
}

const authSessionIsActive = `-- name: AuthSessionIsActive :one
SELECT EXISTS (SELECT 1 FROM auth_sessions
  WHERE id=$1::text AND revoked_at IS NULL AND expires_at > clock_timestamp())
`

// A VoiceSession whose login session was revoked, expired or deleted closes.
func (q *Queries) AuthSessionIsActive(ctx context.Context, authSessionID pgtype.Text) (bool, error) {
	row := q.db.QueryRow(ctx, authSessionIsActive, authSessionID)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const claimVoiceMediaMaterialization = `-- name: ClaimVoiceMediaMaterialization :one
UPDATE capture_sessions
SET materialize_attempts=materialize_attempts+1
WHERE id=$1 AND materialize_requested_at IS NOT NULL
  AND (status='finalizing' OR (status='recovering' AND transcript_recovered_at IS NOT NULL))
  AND (materialize_retry_at IS NULL OR materialize_retry_at<=clock_timestamp())
RETURNING materialize_attempts,materialize_requested_at
`

type ClaimVoiceMediaMaterializationRow struct {
	MaterializeAttempts    int32              `json:"materialize_attempts"`
	MaterializeRequestedAt pgtype.Timestamptz `json:"materialize_requested_at"`
}

// Takes the Capture's due final materialization and counts the attempt.
// Its River job is the only runner.
func (q *Queries) ClaimVoiceMediaMaterialization(ctx context.Context, id string) (ClaimVoiceMediaMaterializationRow, error) {
	row := q.db.QueryRow(ctx, claimVoiceMediaMaterialization, id)
	var i ClaimVoiceMediaMaterializationRow
	err := row.Scan(&i.MaterializeAttempts, &i.MaterializeRequestedAt)
	return i, err
}

const claimVoiceSessionReconcile = `-- name: ClaimVoiceSessionReconcile :one
UPDATE voice_sessions
SET updated_at=clock_timestamp()
WHERE id=$1::text
  AND status IN ('provisioning','connected','reconnecting','closing')
  AND updated_at < clock_timestamp()-CASE
    WHEN last_failure_code='publisher_absent' AND status<>'closing' THEN interval '60 seconds'
    ELSE $2::interval
  END
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

type ClaimVoiceSessionReconcileParams struct {
	ID     string          `json:"id"`
	MinAge pgtype.Interval `json:"min_age"`
}

// Takes an open session that no write touched for the reconcile interval; a
// session whose publisher is absent waits a minute.
func (q *Queries) ClaimVoiceSessionReconcile(ctx context.Context, arg ClaimVoiceSessionReconcileParams) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, claimVoiceSessionReconcile, arg.ID, arg.MinAge)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const claimVoiceTranscriptEpoch = `-- name: ClaimVoiceTranscriptEpoch :one
UPDATE voice_sessions
SET next_media_epoch=next_media_epoch+1
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
RETURNING (next_media_epoch-1)::integer AS media_epoch
`

// Each claim returns a number no earlier claim for the session returned, even
// across runtime restarts, so transcript coverage streams never collide. It
// leaves updated_at alone: the reconcile worker reads it as publisher activity.
func (q *Queries) ClaimVoiceTranscriptEpoch(ctx context.Context, id string) (int32, error) {
	row := q.db.QueryRow(ctx, claimVoiceTranscriptEpoch, id)
	var media_epoch int32
	err := row.Scan(&media_epoch)
	return media_epoch, err
}

const clearConfirmedVoicePartialTranscript = `-- name: ClearConfirmedVoicePartialTranscript :exec
UPDATE voice_sessions
SET latest_partial_text=NULL,latest_partial_start_offset_ms=NULL,
    latest_partial_end_offset_ms=NULL,latest_partial_updated_at=NULL,updated_at=clock_timestamp()
WHERE id=$1 AND latest_partial_end_offset_ms <= $2
`

type ClearConfirmedVoicePartialTranscriptParams struct {
	ID                       string      `json:"id"`
	LatestPartialEndOffsetMs pgtype.Int8 `json:"latest_partial_end_offset_ms"`
}

func (q *Queries) ClearConfirmedVoicePartialTranscript(ctx context.Context, arg ClearConfirmedVoicePartialTranscriptParams) error {
	_, err := q.db.Exec(ctx, clearConfirmedVoicePartialTranscript, arg.ID, arg.LatestPartialEndOffsetMs)
	return err
}

const clearVoiceSessionPartialTranscript = `-- name: ClearVoiceSessionPartialTranscript :one
UPDATE voice_sessions
SET latest_partial_text=NULL,latest_partial_start_offset_ms=NULL,
    latest_partial_end_offset_ms=NULL,latest_partial_updated_at=NULL,updated_at=clock_timestamp()
WHERE id=$1
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

func (q *Queries) ClearVoiceSessionPartialTranscript(ctx context.Context, id string) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, clearVoiceSessionPartialTranscript, id)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const closeVoiceSession = `-- name: CloseVoiceSession :one
UPDATE voice_sessions
SET status='closed',closed_at=coalesce(closed_at,clock_timestamp()),updated_at=clock_timestamp(),
    latest_partial_text=NULL,latest_partial_start_offset_ms=NULL,
    latest_partial_end_offset_ms=NULL,latest_partial_updated_at=NULL
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing','closed')
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

// A closed session keeps no partial text (M11-N16).
func (q *Queries) CloseVoiceSession(ctx context.Context, id string) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, closeVoiceSession, id)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const createCaptureMediaOutput = `-- name: CreateCaptureMediaOutput :one
INSERT INTO capture_media_outputs(
  id,capture_session_id,purpose,range_digest,object_key,filename,media_type,
  duration_ms,size_bytes,sha256
) VALUES($1,$2,$3,$4,$5,$6,'audio/mp4',$7,$8,$9)
ON CONFLICT(capture_session_id,purpose,range_digest) DO UPDATE
SET object_key=EXCLUDED.object_key
WHERE capture_media_outputs.object_key=EXCLUDED.object_key
  AND capture_media_outputs.duration_ms=EXCLUDED.duration_ms
  AND capture_media_outputs.size_bytes=EXCLUDED.size_bytes
  AND capture_media_outputs.sha256=EXCLUDED.sha256
RETURNING id, capture_session_id, purpose, range_digest, object_key, filename, media_type, duration_ms, size_bytes, sha256, document_id, document_version_id, created_at
`

type CreateCaptureMediaOutputParams struct {
	ID               string `json:"id"`
	CaptureSessionID string `json:"capture_session_id"`
	Purpose          string `json:"purpose"`
	RangeDigest      string `json:"range_digest"`
	ObjectKey        string `json:"object_key"`
	Filename         string `json:"filename"`
	DurationMs       int64  `json:"duration_ms"`
	SizeBytes        int64  `json:"size_bytes"`
	Sha256           string `json:"sha256"`
}

func (q *Queries) CreateCaptureMediaOutput(ctx context.Context, arg CreateCaptureMediaOutputParams) (CaptureMediaOutput, error) {
	row := q.db.QueryRow(ctx, createCaptureMediaOutput,
		arg.ID,
		arg.CaptureSessionID,
		arg.Purpose,
		arg.RangeDigest,
		arg.ObjectKey,
		arg.Filename,
		arg.DurationMs,
		arg.SizeBytes,
		arg.Sha256,
	)
	var i CaptureMediaOutput
	err := row.Scan(
		&i.ID,
		&i.CaptureSessionID,
		&i.Purpose,
		&i.RangeDigest,
		&i.ObjectKey,
		&i.Filename,
		&i.MediaType,
		&i.DurationMs,
		&i.SizeBytes,
		&i.Sha256,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.CreatedAt,
	)
	return i, err
}

const createCaptureMediaRange = `-- name: CreateCaptureMediaRange :one
INSERT INTO capture_media_ranges(
  id,capture_session_id,epoch_id,kind,start_offset_ms,end_offset_ms,reason
) VALUES($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT(capture_session_id,kind,start_offset_ms,end_offset_ms) DO UPDATE
SET reason=EXCLUDED.reason
WHERE capture_media_ranges.epoch_id IS NOT DISTINCT FROM EXCLUDED.epoch_id
RETURNING id, capture_session_id, epoch_id, kind, start_offset_ms, end_offset_ms, reason, created_at
`

type CreateCaptureMediaRangeParams struct {
	ID               string      `json:"id"`
	CaptureSessionID string      `json:"capture_session_id"`
	EpochID          pgtype.Text `json:"epoch_id"`
	Kind             string      `json:"kind"`
	StartOffsetMs    int64       `json:"start_offset_ms"`
	EndOffsetMs      int64       `json:"end_offset_ms"`
	Reason           string      `json:"reason"`
}

func (q *Queries) CreateCaptureMediaRange(ctx context.Context, arg CreateCaptureMediaRangeParams) (CaptureMediaRange, error) {
	row := q.db.QueryRow(ctx, createCaptureMediaRange,
		arg.ID,
		arg.CaptureSessionID,
		arg.EpochID,
		arg.Kind,
		arg.StartOffsetMs,
		arg.EndOffsetMs,
		arg.Reason,
	)
	var i CaptureMediaRange
	err := row.Scan(
		&i.ID,
		&i.CaptureSessionID,
		&i.EpochID,
		&i.Kind,
		&i.StartOffsetMs,
		&i.EndOffsetMs,
		&i.Reason,
		&i.CreatedAt,
	)
	return i, err
}

const createLiveKitCaptureSession = `-- name: CreateLiveKitCaptureSession :one
WITH voice AS (
  SELECT session.id, session.tenant_id, session.room_id, session.created_by_actor_id, session.status, session.provider_room_name, session.participant_identity, session.credential_generation, session.last_failure_code, session.created_at, session.updated_at, session.closed_at, session.latest_partial_text, session.latest_partial_start_offset_ms, session.latest_partial_end_offset_ms, session.latest_partial_updated_at, session.last_input_started_ms, session.last_input_ended_ms, session.purpose, session.auth_session_id, session.live_agent_actor_id, session.live_lease_until, session.next_media_epoch
  FROM voice_sessions session
  JOIN actors caller
    ON caller.id=session.created_by_actor_id
   AND caller.account_id=$3::text
   AND caller.kind='human'
  JOIN active_room_members membership
    ON membership.room_id=session.room_id AND membership.actor_id=caller.id
  WHERE session.id=$4::text
    AND session.room_id=$5::text
    AND session.status IN ('provisioning','connected','reconnecting')
    AND session.purpose='hardware_control'
)
INSERT INTO capture_sessions(
  id,tenant_id,room_id,created_by_actor_id,status,
  voice_session_id,transcript_start_offset_ms,requested_transcript_start_offset_ms
)
SELECT $1::text,voice.tenant_id,voice.room_id,voice.created_by_actor_id,
  'starting',voice.id,$2::bigint,$2::bigint
FROM voice
RETURNING id, tenant_id, room_id, created_by_actor_id, status, created_at, updated_at, transcript_start_offset_ms, transcript_end_offset_ms, document_id, document_version_id, transcript_document_id, transcript_document_version_id, voice_session_id, transcript_integrity_lost, source_audio_document_id, source_audio_document_version_id, transcript_recovered_at, requested_transcript_start_offset_ms, voice_completion_attempts, voice_completion_failed_at, voice_completion_failure_code, staging_deleted_at, stop_requested_at, materialize_requested_at, materialize_attempts, materialize_retry_at, transcript_recovery_status, transcript_recovery_progress_ms, transcript_recovery_total_ms, transcript_recovery_failures, transcript_recovery_failure_code, transcript_recovery_retry_at, hidden_at, quick_notes_state, quick_notes
`

type CreateLiveKitCaptureSessionParams struct {
	ID             string `json:"id"`
	StartOffsetMs  int64  `json:"start_offset_ms"`
	AccountID      string `json:"account_id"`
	VoiceSessionID string `json:"voice_session_id"`
	RoomID         string `json:"room_id"`
}

func (q *Queries) CreateLiveKitCaptureSession(ctx context.Context, arg CreateLiveKitCaptureSessionParams) (CaptureSession, error) {
	row := q.db.QueryRow(ctx, createLiveKitCaptureSession,
		arg.ID,
		arg.StartOffsetMs,
		arg.AccountID,
		arg.VoiceSessionID,
		arg.RoomID,
	)
	var i CaptureSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const createVoiceMediaEpoch = `-- name: CreateVoiceMediaEpoch :one
INSERT INTO voice_media_epochs(
  id,voice_session_id,capture_session_id,epoch_index,desired_state,observed_state,staging_prefix
) VALUES(
  $1::text,$2::text,$3::text,
  $4::integer,'active','requested',$5::text
)
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type CreateVoiceMediaEpochParams struct {
	ID               string `json:"id"`
	VoiceSessionID   string `json:"voice_session_id"`
	CaptureSessionID string `json:"capture_session_id"`
	EpochIndex       int32  `json:"epoch_index"`
	StagingPrefix    string `json:"staging_prefix"`
}

func (q *Queries) CreateVoiceMediaEpoch(ctx context.Context, arg CreateVoiceMediaEpochParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, createVoiceMediaEpoch,
		arg.ID,
		arg.VoiceSessionID,
		arg.CaptureSessionID,
		arg.EpochIndex,
		arg.StagingPrefix,
	)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const createVoiceSession = `-- name: CreateVoiceSession :one
WITH authority AS (
  SELECT room.tenant_id,caller.id AS actor_id
  FROM rooms room
  JOIN actors caller
    ON caller.tenant_id=room.tenant_id
   AND caller.account_id=$7::text
   AND caller.kind='human'
  JOIN active_room_members membership
    ON membership.room_id=room.id AND membership.actor_id=caller.id
  WHERE room.id=$2::text AND room.deleted_at IS NULL
    -- Dictation sends ordinary chat Messages, so any member Room accepts it
    -- except an Agent direct Room whose Agent is no longer active.
    AND ($5::text='hardware_control'
      OR room.direct_agent_actor_id IS NULL
      OR EXISTS (SELECT 1 FROM agent_registrations registration
        WHERE registration.actor_id=room.direct_agent_actor_id
          AND registration.tenant_id=room.tenant_id AND registration.status='active'))
)
INSERT INTO voice_sessions(
  id,tenant_id,room_id,created_by_actor_id,status,provider_room_name,participant_identity,
  purpose,auth_session_id
)
SELECT $1::text,authority.tenant_id,$2::text,authority.actor_id,
  'provisioning',$3::text,$4::text,
  $5::text,$6::text
FROM authority
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

type CreateVoiceSessionParams struct {
	ID                  string      `json:"id"`
	RoomID              string      `json:"room_id"`
	ProviderRoomName    string      `json:"provider_room_name"`
	ParticipantIdentity string      `json:"participant_identity"`
	Purpose             string      `json:"purpose"`
	AuthSessionID       pgtype.Text `json:"auth_session_id"`
	AccountID           string      `json:"account_id"`
}

func (q *Queries) CreateVoiceSession(ctx context.Context, arg CreateVoiceSessionParams) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, createVoiceSession,
		arg.ID,
		arg.RoomID,
		arg.ProviderRoomName,
		arg.ParticipantIdentity,
		arg.Purpose,
		arg.AuthSessionID,
		arg.AccountID,
	)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const createVoiceTranscriptSegment = `-- name: CreateVoiceTranscriptSegment :one
WITH writable_capture AS (
  SELECT session.id
  FROM capture_sessions session
  JOIN rooms room
    ON room.id=session.room_id AND room.tenant_id=session.tenant_id AND room.deleted_at IS NULL
  JOIN actors caller
    ON caller.tenant_id=session.tenant_id AND caller.account_id=$13::text AND caller.kind='human'
  JOIN room_members membership
    ON membership.room_id=session.room_id AND membership.actor_id=caller.id
  WHERE session.id=$4::text
    AND session.room_id=$14::text
    AND session.status IN ('starting','recording','finalizing')
    AND (
      session.transcript_end_offset_ms IS NULL OR
      $8::bigint <= session.transcript_end_offset_ms
    )
  FOR NO KEY UPDATE OF session
)
INSERT INTO voice_transcript_segments(
  id,event_id,voice_session_id,capture_session_id,media_epoch,lane,
  start_offset_ms,end_offset_ms,text,normalized_text,kind,speaker_id
) SELECT
  $1::text,$2::text,$3::text,
  $4::text,$5::integer,$6::text,
  $7::bigint,$8::bigint,$9::text,
  $10::text,$11::text,$12::text
WHERE $4::text IS NULL OR EXISTS (SELECT 1 FROM writable_capture)
ON CONFLICT(event_id) DO UPDATE SET text=EXCLUDED.text,
  speaker_id=COALESCE(EXCLUDED.speaker_id,voice_transcript_segments.speaker_id),
  seq=CASE WHEN (voice_transcript_segments.text,voice_transcript_segments.speaker_id)
    IS NOT DISTINCT FROM (EXCLUDED.text,COALESCE(EXCLUDED.speaker_id,voice_transcript_segments.speaker_id))
    THEN voice_transcript_segments.seq ELSE nextval('voice_transcript_segment_seq') END
WHERE voice_transcript_segments.normalized_text=EXCLUDED.normalized_text
  AND voice_transcript_segments.kind=EXCLUDED.kind
  AND (
    voice_transcript_segments.speaker_id IS NOT DISTINCT FROM EXCLUDED.speaker_id
    OR voice_transcript_segments.speaker_id IS NULL
  )
RETURNING id, event_id, voice_session_id, capture_session_id, media_epoch, lane, start_offset_ms, end_offset_ms, text, normalized_text, kind, accepted_at, speaker_id, seq, superseded_at
`

type CreateVoiceTranscriptSegmentParams struct {
	ID               string      `json:"id"`
	EventID          string      `json:"event_id"`
	VoiceSessionID   string      `json:"voice_session_id"`
	CaptureSessionID pgtype.Text `json:"capture_session_id"`
	MediaEpoch       int32       `json:"media_epoch"`
	Lane             string      `json:"lane"`
	StartOffsetMs    int64       `json:"start_offset_ms"`
	EndOffsetMs      int64       `json:"end_offset_ms"`
	Text             string      `json:"text"`
	NormalizedText   string      `json:"normalized_text"`
	Kind             string      `json:"kind"`
	SpeakerID        pgtype.Text `json:"speaker_id"`
	AccountID        string      `json:"account_id"`
	RoomID           string      `json:"room_id"`
}

// The caller holds LockVoiceSession until commit, so seq (the column default)
// grows in commit order within the VoiceSession. A retry that changes the
// words or fills in the speaker takes a new seq so the event feed resends the
// row; an identical retry keeps it. A captured final is written only while
// its Capture still accepts speech up to the final's end; otherwise no row
// is returned and GetVoiceTranscriptSegmentByEvent tells a retry from an
// ignored final.
func (q *Queries) CreateVoiceTranscriptSegment(ctx context.Context, arg CreateVoiceTranscriptSegmentParams) (VoiceTranscriptSegment, error) {
	row := q.db.QueryRow(ctx, createVoiceTranscriptSegment,
		arg.ID,
		arg.EventID,
		arg.VoiceSessionID,
		arg.CaptureSessionID,
		arg.MediaEpoch,
		arg.Lane,
		arg.StartOffsetMs,
		arg.EndOffsetMs,
		arg.Text,
		arg.NormalizedText,
		arg.Kind,
		arg.SpeakerID,
		arg.AccountID,
		arg.RoomID,
	)
	var i VoiceTranscriptSegment
	err := row.Scan(
		&i.ID,
		&i.EventID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.MediaEpoch,
		&i.Lane,
		&i.StartOffsetMs,
		&i.EndOffsetMs,
		&i.Text,
		&i.NormalizedText,
		&i.Kind,
		&i.AcceptedAt,
		&i.SpeakerID,
		&i.Seq,
		&i.SupersededAt,
	)
	return i, err
}

const failLiveKitCaptureTranscriptFinalization = `-- name: FailLiveKitCaptureTranscriptFinalization :one
WITH failed_capture AS (
  UPDATE capture_sessions capture
  SET status='failed',updated_at=clock_timestamp()
  WHERE capture.id=$1::text
    AND capture.materialize_requested_at IS NOT NULL
    AND capture.status='finalizing'
  RETURNING capture.id, capture.tenant_id, capture.room_id, capture.created_by_actor_id, capture.status, capture.created_at, capture.updated_at, capture.transcript_start_offset_ms, capture.transcript_end_offset_ms, capture.document_id, capture.document_version_id, capture.transcript_document_id, capture.transcript_document_version_id, capture.voice_session_id, capture.transcript_integrity_lost, capture.source_audio_document_id, capture.source_audio_document_version_id, capture.transcript_recovered_at, capture.requested_transcript_start_offset_ms, capture.voice_completion_attempts, capture.voice_completion_failed_at, capture.voice_completion_failure_code, capture.staging_deleted_at, capture.stop_requested_at, capture.materialize_requested_at, capture.materialize_attempts, capture.materialize_retry_at, capture.transcript_recovery_status, capture.transcript_recovery_progress_ms, capture.transcript_recovery_total_ms, capture.transcript_recovery_failures, capture.transcript_recovery_failure_code, capture.transcript_recovery_retry_at, capture.hidden_at, capture.quick_notes_state, capture.quick_notes
), marked_epoch AS (
  UPDATE voice_media_epochs epoch
  SET last_failure_code='transcript_unavailable',updated_at=clock_timestamp()
  FROM failed_capture capture
  WHERE epoch.capture_session_id=capture.id
    AND epoch.observed_state='available'
)
SELECT id, tenant_id, room_id, created_by_actor_id, status, created_at, updated_at, transcript_start_offset_ms, transcript_end_offset_ms, document_id, document_version_id, transcript_document_id, transcript_document_version_id, voice_session_id, transcript_integrity_lost, source_audio_document_id, source_audio_document_version_id, transcript_recovered_at, requested_transcript_start_offset_ms, voice_completion_attempts, voice_completion_failed_at, voice_completion_failure_code, staging_deleted_at, stop_requested_at, materialize_requested_at, materialize_attempts, materialize_retry_at, transcript_recovery_status, transcript_recovery_progress_ms, transcript_recovery_total_ms, transcript_recovery_failures, transcript_recovery_failure_code, transcript_recovery_retry_at, hidden_at, quick_notes_state, quick_notes FROM failed_capture
`

type FailLiveKitCaptureTranscriptFinalizationRow struct {
	ID                               string             `json:"id"`
	TenantID                         string             `json:"tenant_id"`
	RoomID                           string             `json:"room_id"`
	CreatedByActorID                 string             `json:"created_by_actor_id"`
	Status                           string             `json:"status"`
	CreatedAt                        pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                        pgtype.Timestamptz `json:"updated_at"`
	TranscriptStartOffsetMs          pgtype.Int8        `json:"transcript_start_offset_ms"`
	TranscriptEndOffsetMs            pgtype.Int8        `json:"transcript_end_offset_ms"`
	DocumentID                       pgtype.Text        `json:"document_id"`
	DocumentVersionID                pgtype.Text        `json:"document_version_id"`
	TranscriptDocumentID             pgtype.Text        `json:"transcript_document_id"`
	TranscriptDocumentVersionID      pgtype.Text        `json:"transcript_document_version_id"`
	VoiceSessionID                   pgtype.Text        `json:"voice_session_id"`
	TranscriptIntegrityLost          bool               `json:"transcript_integrity_lost"`
	SourceAudioDocumentID            pgtype.Text        `json:"source_audio_document_id"`
	SourceAudioDocumentVersionID     pgtype.Text        `json:"source_audio_document_version_id"`
	TranscriptRecoveredAt            pgtype.Timestamptz `json:"transcript_recovered_at"`
	RequestedTranscriptStartOffsetMs int64              `json:"requested_transcript_start_offset_ms"`
	VoiceCompletionAttempts          int32              `json:"voice_completion_attempts"`
	VoiceCompletionFailedAt          pgtype.Timestamptz `json:"voice_completion_failed_at"`
	VoiceCompletionFailureCode       pgtype.Text        `json:"voice_completion_failure_code"`
	StagingDeletedAt                 pgtype.Timestamptz `json:"staging_deleted_at"`
	StopRequestedAt                  pgtype.Timestamptz `json:"stop_requested_at"`
	MaterializeRequestedAt           pgtype.Timestamptz `json:"materialize_requested_at"`
	MaterializeAttempts              int32              `json:"materialize_attempts"`
	MaterializeRetryAt               pgtype.Timestamptz `json:"materialize_retry_at"`
	TranscriptRecoveryStatus         pgtype.Text        `json:"transcript_recovery_status"`
	TranscriptRecoveryProgressMs     int64              `json:"transcript_recovery_progress_ms"`
	TranscriptRecoveryTotalMs        pgtype.Int8        `json:"transcript_recovery_total_ms"`
	TranscriptRecoveryFailures       int32              `json:"transcript_recovery_failures"`
	TranscriptRecoveryFailureCode    pgtype.Text        `json:"transcript_recovery_failure_code"`
	TranscriptRecoveryRetryAt        pgtype.Timestamptz `json:"transcript_recovery_retry_at"`
	HiddenAt                         pgtype.Timestamptz `json:"hidden_at"`
	QuickNotesState                  pgtype.Text        `json:"quick_notes_state"`
	QuickNotes                       []byte             `json:"quick_notes"`
}

func (q *Queries) FailLiveKitCaptureTranscriptFinalization(ctx context.Context, captureSessionID string) (FailLiveKitCaptureTranscriptFinalizationRow, error) {
	row := q.db.QueryRow(ctx, failLiveKitCaptureTranscriptFinalization, captureSessionID)
	var i FailLiveKitCaptureTranscriptFinalizationRow
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const failVoiceMediaEpochWithoutMedia = `-- name: FailVoiceMediaEpochWithoutMedia :exec
WITH target AS MATERIALIZED (
  SELECT epoch.id,epoch.capture_session_id,voice.id AS voice_session_id
  FROM voice_media_epochs epoch JOIN voice_sessions voice ON voice.id=epoch.voice_session_id
  WHERE epoch.id=$1 AND epoch.observed_state IN ('requested','active','sealing','unknown','failed')
  FOR NO KEY UPDATE OF voice
), failed_epoch AS (
  UPDATE voice_media_epochs epoch
  SET observed_state='failed',desired_state='sealed',last_failure_code='egress_failed_without_media',
      restart_retry_at=NULL,updated_at=clock_timestamp()
  FROM target WHERE epoch.id=target.id RETURNING epoch.capture_session_id,epoch.voice_session_id
), failed_capture AS (
  UPDATE capture_sessions capture SET status='failed',updated_at=clock_timestamp()
  FROM failed_epoch WHERE capture.id=failed_epoch.capture_session_id
    AND capture.status IN ('starting','recording','finalizing')
  RETURNING capture.id,capture.voice_session_id
)
UPDATE voice_sessions voice SET status='closing',last_failure_code='egress_failed_without_media',updated_at=clock_timestamp()
FROM failed_capture WHERE voice.id=failed_capture.voice_session_id
  AND voice.status IN ('provisioning','connected','reconnecting')
`

func (q *Queries) FailVoiceMediaEpochWithoutMedia(ctx context.Context, id string) error {
	_, err := q.db.Exec(ctx, failVoiceMediaEpochWithoutMedia, id)
	return err
}

const failVoiceMediaMaterialization = `-- name: FailVoiceMediaMaterialization :one
UPDATE capture_sessions
SET status='failed',updated_at=clock_timestamp()
WHERE id=$1 AND materialize_requested_at IS NOT NULL
  AND status IN ('finalizing','recovering')
RETURNING id,tenant_id,room_id,created_by_actor_id
`

type FailVoiceMediaMaterializationRow struct {
	ID               string `json:"id"`
	TenantID         string `json:"tenant_id"`
	RoomID           string `json:"room_id"`
	CreatedByActorID string `json:"created_by_actor_id"`
}

func (q *Queries) FailVoiceMediaMaterialization(ctx context.Context, id string) (FailVoiceMediaMaterializationRow, error) {
	row := q.db.QueryRow(ctx, failVoiceMediaMaterialization, id)
	var i FailVoiceMediaMaterializationRow
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
	)
	return i, err
}

const finalizeLiveKitCapture = `-- name: FinalizeLiveKitCapture :one
UPDATE capture_sessions
SET status='finalized',document_id=$2,document_version_id=$3,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('finalizing','recovering')
  AND (NOT transcript_integrity_lost OR transcript_recovered_at IS NOT NULL)
RETURNING id, tenant_id, room_id, created_by_actor_id, status, created_at, updated_at, transcript_start_offset_ms, transcript_end_offset_ms, document_id, document_version_id, transcript_document_id, transcript_document_version_id, voice_session_id, transcript_integrity_lost, source_audio_document_id, source_audio_document_version_id, transcript_recovered_at, requested_transcript_start_offset_ms, voice_completion_attempts, voice_completion_failed_at, voice_completion_failure_code, staging_deleted_at, stop_requested_at, materialize_requested_at, materialize_attempts, materialize_retry_at, transcript_recovery_status, transcript_recovery_progress_ms, transcript_recovery_total_ms, transcript_recovery_failures, transcript_recovery_failure_code, transcript_recovery_retry_at, hidden_at, quick_notes_state, quick_notes
`

type FinalizeLiveKitCaptureParams struct {
	ID                string      `json:"id"`
	DocumentID        pgtype.Text `json:"document_id"`
	DocumentVersionID pgtype.Text `json:"document_version_id"`
}

func (q *Queries) FinalizeLiveKitCapture(ctx context.Context, arg FinalizeLiveKitCaptureParams) (CaptureSession, error) {
	row := q.db.QueryRow(ctx, finalizeLiveKitCapture, arg.ID, arg.DocumentID, arg.DocumentVersionID)
	var i CaptureSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const getActiveLiveKitCaptureForAccountRoom = `-- name: GetActiveLiveKitCaptureForAccountRoom :one
SELECT capture.id, capture.tenant_id, capture.room_id, capture.created_by_actor_id, capture.status, capture.created_at, capture.updated_at, capture.transcript_start_offset_ms, capture.transcript_end_offset_ms, capture.document_id, capture.document_version_id, capture.transcript_document_id, capture.transcript_document_version_id, capture.voice_session_id, capture.transcript_integrity_lost, capture.source_audio_document_id, capture.source_audio_document_version_id, capture.transcript_recovered_at, capture.requested_transcript_start_offset_ms, capture.voice_completion_attempts, capture.voice_completion_failed_at, capture.voice_completion_failure_code, capture.staging_deleted_at, capture.stop_requested_at, capture.materialize_requested_at, capture.materialize_attempts, capture.materialize_retry_at, capture.transcript_recovery_status, capture.transcript_recovery_progress_ms, capture.transcript_recovery_total_ms, capture.transcript_recovery_failures, capture.transcript_recovery_failure_code, capture.transcript_recovery_retry_at, capture.hidden_at, capture.quick_notes_state, capture.quick_notes
FROM capture_sessions capture
JOIN actors caller
  ON caller.id=capture.created_by_actor_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=capture.room_id AND membership.actor_id=caller.id
WHERE capture.room_id=$2::text
  AND (capture.status IN ('starting','recording','finalizing','recovering') OR (capture.status='finalized' AND capture.transcript_document_version_id IS NULL AND capture.voice_completion_failed_at IS NULL))
ORDER BY (capture.status IN ('starting','recording','finalizing')) DESC,capture.created_at DESC
LIMIT 1
`

type GetActiveLiveKitCaptureForAccountRoomParams struct {
	AccountID string `json:"account_id"`
	RoomID    string `json:"room_id"`
}

func (q *Queries) GetActiveLiveKitCaptureForAccountRoom(ctx context.Context, arg GetActiveLiveKitCaptureForAccountRoomParams) (CaptureSession, error) {
	row := q.db.QueryRow(ctx, getActiveLiveKitCaptureForAccountRoom, arg.AccountID, arg.RoomID)
	var i CaptureSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const getActiveLiveKitCaptureForVoiceSession = `-- name: GetActiveLiveKitCaptureForVoiceSession :one
SELECT id, tenant_id, room_id, created_by_actor_id, status, created_at, updated_at, transcript_start_offset_ms, transcript_end_offset_ms, document_id, document_version_id, transcript_document_id, transcript_document_version_id, voice_session_id, transcript_integrity_lost, source_audio_document_id, source_audio_document_version_id, transcript_recovered_at, requested_transcript_start_offset_ms, voice_completion_attempts, voice_completion_failed_at, voice_completion_failure_code, staging_deleted_at, stop_requested_at, materialize_requested_at, materialize_attempts, materialize_retry_at, transcript_recovery_status, transcript_recovery_progress_ms, transcript_recovery_total_ms, transcript_recovery_failures, transcript_recovery_failure_code, transcript_recovery_retry_at, hidden_at, quick_notes_state, quick_notes FROM capture_sessions
WHERE voice_session_id=$1
  AND (status IN ('starting','recording','finalizing') OR (status='finalized' AND transcript_document_version_id IS NULL AND voice_completion_failed_at IS NULL))
LIMIT 1
`

func (q *Queries) GetActiveLiveKitCaptureForVoiceSession(ctx context.Context, voiceSessionID pgtype.Text) (CaptureSession, error) {
	row := q.db.QueryRow(ctx, getActiveLiveKitCaptureForVoiceSession, voiceSessionID)
	var i CaptureSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const getActiveRecordingSessionForAuthSessionRoom = `-- name: GetActiveRecordingSessionForAuthSessionRoom :one
SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch
FROM voice_sessions voice
JOIN actors caller
  ON caller.id=voice.created_by_actor_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=voice.room_id AND membership.actor_id=caller.id
WHERE voice.room_id=$2::text
  AND voice.auth_session_id=$3::text
  AND voice.purpose='hardware_control'
  AND voice.status IN ('provisioning','connected','reconnecting','closing')
`

type GetActiveRecordingSessionForAuthSessionRoomParams struct {
	AccountID     string `json:"account_id"`
	RoomID        string `json:"room_id"`
	AuthSessionID string `json:"auth_session_id"`
}

// The recording window resumes only this login session's recording session;
// a dictation session is never reused for a recording.
func (q *Queries) GetActiveRecordingSessionForAuthSessionRoom(ctx context.Context, arg GetActiveRecordingSessionForAuthSessionRoomParams) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, getActiveRecordingSessionForAuthSessionRoom, arg.AccountID, arg.RoomID, arg.AuthSessionID)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const getCaptureGapSummary = `-- name: GetCaptureGapSummary :one
SELECT count(*)::bigint AS gap_count,
       coalesce(sum(end_offset_ms-start_offset_ms),0)::bigint AS gap_duration_ms
FROM capture_media_ranges
WHERE capture_session_id=$1 AND kind='gap'
`

type GetCaptureGapSummaryRow struct {
	GapCount      int64 `json:"gap_count"`
	GapDurationMs int64 `json:"gap_duration_ms"`
}

func (q *Queries) GetCaptureGapSummary(ctx context.Context, captureSessionID string) (GetCaptureGapSummaryRow, error) {
	row := q.db.QueryRow(ctx, getCaptureGapSummary, captureSessionID)
	var i GetCaptureGapSummaryRow
	err := row.Scan(&i.GapCount, &i.GapDurationMs)
	return i, err
}

const getCaptureMediaOutput = `-- name: GetCaptureMediaOutput :one
SELECT id, capture_session_id, purpose, range_digest, object_key, filename, media_type, duration_ms, size_bytes, sha256, document_id, document_version_id, created_at FROM capture_media_outputs
WHERE capture_session_id=$1 AND purpose=$2 AND range_digest=$3
`

type GetCaptureMediaOutputParams struct {
	CaptureSessionID string `json:"capture_session_id"`
	Purpose          string `json:"purpose"`
	RangeDigest      string `json:"range_digest"`
}

func (q *Queries) GetCaptureMediaOutput(ctx context.Context, arg GetCaptureMediaOutputParams) (CaptureMediaOutput, error) {
	row := q.db.QueryRow(ctx, getCaptureMediaOutput, arg.CaptureSessionID, arg.Purpose, arg.RangeDigest)
	var i CaptureMediaOutput
	err := row.Scan(
		&i.ID,
		&i.CaptureSessionID,
		&i.Purpose,
		&i.RangeDigest,
		&i.ObjectKey,
		&i.Filename,
		&i.MediaType,
		&i.DurationMs,
		&i.SizeBytes,
		&i.Sha256,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.CreatedAt,
	)
	return i, err
}

const getFinalCaptureMediaOutput = `-- name: GetFinalCaptureMediaOutput :one
SELECT id, capture_session_id, purpose, range_digest, object_key, filename, media_type, duration_ms, size_bytes, sha256, document_id, document_version_id, created_at FROM capture_media_outputs
WHERE capture_session_id=$1 AND purpose='final'
`

func (q *Queries) GetFinalCaptureMediaOutput(ctx context.Context, captureSessionID string) (CaptureMediaOutput, error) {
	row := q.db.QueryRow(ctx, getFinalCaptureMediaOutput, captureSessionID)
	var i CaptureMediaOutput
	err := row.Scan(
		&i.ID,
		&i.CaptureSessionID,
		&i.Purpose,
		&i.RangeDigest,
		&i.ObjectKey,
		&i.Filename,
		&i.MediaType,
		&i.DurationMs,
		&i.SizeBytes,
		&i.Sha256,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.CreatedAt,
	)
	return i, err
}

const getLatestVoiceMediaEpochForCapture = `-- name: GetLatestVoiceMediaEpochForCapture :one
SELECT id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at FROM voice_media_epochs
WHERE capture_session_id=$1
ORDER BY epoch_index DESC
LIMIT 1
`

func (q *Queries) GetLatestVoiceMediaEpochForCapture(ctx context.Context, captureSessionID string) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, getLatestVoiceMediaEpochForCapture, captureSessionID)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const getOwedVoiceMediaStop = `-- name: GetOwedVoiceMediaStop :one
SELECT epoch.id, epoch.voice_session_id, epoch.capture_session_id, epoch.epoch_index, epoch.desired_state, epoch.observed_state, epoch.provider_egress_id, epoch.staging_prefix, epoch.playlist_object_key, epoch.first_archived_ms, epoch.archived_through_ms, epoch.segment_count, epoch.last_segment_at, epoch.final_end_ms, epoch.last_failure_code, epoch.created_at, epoch.updated_at, epoch.sealed_at, epoch.recorder_state, epoch.recorder_started_at, epoch.recorder_archived_through_ms, epoch.recorder_failure_code, epoch.recorder_reported_at, epoch.restart_retry_at FROM capture_sessions capture
JOIN LATERAL (
  SELECT id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at FROM voice_media_epochs WHERE capture_session_id=capture.id
  ORDER BY epoch_index DESC LIMIT 1
) epoch ON true
WHERE capture.id=$1 AND capture.status='finalizing' AND capture.stop_requested_at IS NOT NULL
  AND epoch.desired_state='sealed' AND epoch.provider_egress_id IS NOT NULL
  AND epoch.observed_state IN ('requested','active','sealing','unknown')
`

// Returns the last recorder epoch of a stopped Capture while its recorder is
// known and still has to be stopped.
func (q *Queries) GetOwedVoiceMediaStop(ctx context.Context, id string) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, getOwedVoiceMediaStop, id)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const getPendingLiveKitCaptureCompletion = `-- name: GetPendingLiveKitCaptureCompletion :one
SELECT capture.id,capture.tenant_id,capture.room_id,capture.created_by_actor_id,
       actor.account_id,capture.document_id,capture.document_version_id,
       capture.voice_completion_attempts
FROM capture_sessions capture
JOIN actors actor
  ON actor.id=capture.created_by_actor_id AND actor.tenant_id=capture.tenant_id AND actor.kind='human'
  AND actor.account_id IS NOT NULL
JOIN active_room_members member ON member.room_id=capture.room_id AND member.actor_id=actor.id
JOIN rooms room ON room.id=capture.room_id AND room.deleted_at IS NULL
WHERE capture.id=$1
  AND capture.status='finalized'
  AND capture.document_id IS NOT NULL
  AND capture.document_version_id IS NOT NULL
  AND capture.transcript_document_id IS NULL
  AND capture.transcript_document_version_id IS NULL
  AND capture.voice_completion_failed_at IS NULL
`

type GetPendingLiveKitCaptureCompletionRow struct {
	ID                      string      `json:"id"`
	TenantID                string      `json:"tenant_id"`
	RoomID                  string      `json:"room_id"`
	CreatedByActorID        string      `json:"created_by_actor_id"`
	AccountID               pgtype.Text `json:"account_id"`
	DocumentID              pgtype.Text `json:"document_id"`
	DocumentVersionID       pgtype.Text `json:"document_version_id"`
	VoiceCompletionAttempts int32       `json:"voice_completion_attempts"`
}

// Reads a finalized Capture whose completion is still owed, with the account
// that completes it.
func (q *Queries) GetPendingLiveKitCaptureCompletion(ctx context.Context, id string) (GetPendingLiveKitCaptureCompletionRow, error) {
	row := q.db.QueryRow(ctx, getPendingLiveKitCaptureCompletion, id)
	var i GetPendingLiveKitCaptureCompletionRow
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.AccountID,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.VoiceCompletionAttempts,
	)
	return i, err
}

const getVoiceMediaEpoch = `-- name: GetVoiceMediaEpoch :one
SELECT id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at FROM voice_media_epochs WHERE id=$1
`

func (q *Queries) GetVoiceMediaEpoch(ctx context.Context, id string) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, getVoiceMediaEpoch, id)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const getVoiceMediaMaterializationContext = `-- name: GetVoiceMediaMaterializationContext :one
SELECT capture.id AS capture_session_id,capture.tenant_id,capture.room_id,capture.created_by_actor_id,
       capture.materialize_requested_at,actor.account_id,
       range.start_offset_ms,range.end_offset_ms
FROM capture_sessions capture
JOIN actors actor ON actor.id=capture.created_by_actor_id AND actor.tenant_id=capture.tenant_id
JOIN LATERAL (
  SELECT min(start_offset_ms)::bigint AS start_offset_ms,
         max(end_offset_ms)::bigint AS end_offset_ms
  FROM capture_media_ranges
  WHERE capture_session_id=capture.id AND kind='media'
) range ON true
WHERE capture.id=$1 AND capture.materialize_requested_at IS NOT NULL
`

type GetVoiceMediaMaterializationContextRow struct {
	CaptureSessionID       string             `json:"capture_session_id"`
	TenantID               string             `json:"tenant_id"`
	RoomID                 string             `json:"room_id"`
	CreatedByActorID       string             `json:"created_by_actor_id"`
	MaterializeRequestedAt pgtype.Timestamptz `json:"materialize_requested_at"`
	AccountID              pgtype.Text        `json:"account_id"`
	StartOffsetMs          int64              `json:"start_offset_ms"`
	EndOffsetMs            int64              `json:"end_offset_ms"`
}

func (q *Queries) GetVoiceMediaMaterializationContext(ctx context.Context, id string) (GetVoiceMediaMaterializationContextRow, error) {
	row := q.db.QueryRow(ctx, getVoiceMediaMaterializationContext, id)
	var i GetVoiceMediaMaterializationContextRow
	err := row.Scan(
		&i.CaptureSessionID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.MaterializeRequestedAt,
		&i.AccountID,
		&i.StartOffsetMs,
		&i.EndOffsetMs,
	)
	return i, err
}

const getVoiceMediaPolicyForAccount = `-- name: GetVoiceMediaPolicyForAccount :one
SELECT caller.id AS actor_id,
  coalesce((SELECT voice.room_id FROM voice_sessions voice WHERE voice.created_by_actor_id=caller.id
    AND voice.auth_session_id=$1::text AND voice.purpose='hardware_control'
    AND voice.status IN ('provisioning','connected','reconnecting','closing')
    ORDER BY voice.created_at DESC LIMIT 1),'')::text AS livekit_room_id
FROM actors caller
WHERE caller.tenant_id=$2::text AND caller.account_id=$3::text AND caller.kind='human'
`

type GetVoiceMediaPolicyForAccountParams struct {
	AuthSessionID string `json:"auth_session_id"`
	TenantID      string `json:"tenant_id"`
	AccountID     string `json:"account_id"`
}

type GetVoiceMediaPolicyForAccountRow struct {
	ActorID       string `json:"actor_id"`
	LivekitRoomID string `json:"livekit_room_id"`
}

func (q *Queries) GetVoiceMediaPolicyForAccount(ctx context.Context, arg GetVoiceMediaPolicyForAccountParams) (GetVoiceMediaPolicyForAccountRow, error) {
	row := q.db.QueryRow(ctx, getVoiceMediaPolicyForAccount, arg.AuthSessionID, arg.TenantID, arg.AccountID)
	var i GetVoiceMediaPolicyForAccountRow
	err := row.Scan(&i.ActorID, &i.LivekitRoomID)
	return i, err
}

const getVoiceRuntimeSessionContext = `-- name: GetVoiceRuntimeSessionContext :one
SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch,actor.account_id
FROM voice_sessions voice
JOIN actors actor
  ON actor.id=voice.created_by_actor_id AND actor.tenant_id=voice.tenant_id AND actor.kind='human'
JOIN active_room_members member ON member.room_id=voice.room_id AND member.actor_id=actor.id
JOIN rooms room ON room.id=voice.room_id AND room.deleted_at IS NULL
WHERE voice.id=$1 AND voice.status IN ('provisioning','connected','reconnecting','closing')
  AND (voice.purpose='hardware_control' OR room.direct_agent_actor_id IS NULL OR EXISTS (
    SELECT 1 FROM agent_registrations registration
    WHERE registration.actor_id=room.direct_agent_actor_id
      AND registration.tenant_id=room.tenant_id AND registration.status='active'
  ))
`

type GetVoiceRuntimeSessionContextRow struct {
	ID                         string             `json:"id"`
	TenantID                   string             `json:"tenant_id"`
	RoomID                     string             `json:"room_id"`
	CreatedByActorID           string             `json:"created_by_actor_id"`
	Status                     string             `json:"status"`
	ProviderRoomName           string             `json:"provider_room_name"`
	ParticipantIdentity        string             `json:"participant_identity"`
	CredentialGeneration       int64              `json:"credential_generation"`
	LastFailureCode            pgtype.Text        `json:"last_failure_code"`
	CreatedAt                  pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                  pgtype.Timestamptz `json:"updated_at"`
	ClosedAt                   pgtype.Timestamptz `json:"closed_at"`
	LatestPartialText          pgtype.Text        `json:"latest_partial_text"`
	LatestPartialStartOffsetMs pgtype.Int8        `json:"latest_partial_start_offset_ms"`
	LatestPartialEndOffsetMs   pgtype.Int8        `json:"latest_partial_end_offset_ms"`
	LatestPartialUpdatedAt     pgtype.Timestamptz `json:"latest_partial_updated_at"`
	LastInputStartedMs         pgtype.Int8        `json:"last_input_started_ms"`
	LastInputEndedMs           pgtype.Int8        `json:"last_input_ended_ms"`
	Purpose                    string             `json:"purpose"`
	AuthSessionID              pgtype.Text        `json:"auth_session_id"`
	LiveAgentActorID           pgtype.Text        `json:"live_agent_actor_id"`
	LiveLeaseUntil             pgtype.Timestamptz `json:"live_lease_until"`
	NextMediaEpoch             int32              `json:"next_media_epoch"`
	AccountID                  pgtype.Text        `json:"account_id"`
}

func (q *Queries) GetVoiceRuntimeSessionContext(ctx context.Context, id string) (GetVoiceRuntimeSessionContextRow, error) {
	row := q.db.QueryRow(ctx, getVoiceRuntimeSessionContext, id)
	var i GetVoiceRuntimeSessionContextRow
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
		&i.AccountID,
	)
	return i, err
}

const getVoiceSessionForAccount = `-- name: GetVoiceSessionForAccount :one
SELECT voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch
FROM voice_sessions voice
JOIN actors caller
  ON caller.id=voice.created_by_actor_id AND caller.tenant_id=voice.tenant_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=voice.room_id AND membership.actor_id=caller.id
JOIN rooms room ON room.id=voice.room_id AND room.deleted_at IS NULL
WHERE voice.id=$2::text
  AND (voice.purpose='hardware_control' OR room.direct_agent_actor_id IS NULL OR EXISTS (
    SELECT 1 FROM agent_registrations registration
    WHERE registration.actor_id=room.direct_agent_actor_id
      AND registration.tenant_id=room.tenant_id AND registration.status='active'
  ))
`

type GetVoiceSessionForAccountParams struct {
	AccountID string `json:"account_id"`
	ID        string `json:"id"`
}

func (q *Queries) GetVoiceSessionForAccount(ctx context.Context, arg GetVoiceSessionForAccountParams) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, getVoiceSessionForAccount, arg.AccountID, arg.ID)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const getVoiceSessionPartialForAccount = `-- name: GetVoiceSessionPartialForAccount :one
SELECT voice.latest_partial_text,voice.latest_partial_start_offset_ms,
       voice.latest_partial_end_offset_ms,voice.latest_partial_updated_at
FROM voice_sessions voice
JOIN actors caller ON caller.id=voice.created_by_actor_id
  AND caller.account_id=$1::text AND caller.kind='human'
JOIN active_room_members membership ON membership.room_id=voice.room_id AND membership.actor_id=caller.id
JOIN rooms room ON room.id=voice.room_id AND room.deleted_at IS NULL
WHERE voice.id=$2::text
`

type GetVoiceSessionPartialForAccountParams struct {
	AccountID      string `json:"account_id"`
	VoiceSessionID string `json:"voice_session_id"`
}

type GetVoiceSessionPartialForAccountRow struct {
	LatestPartialText          pgtype.Text        `json:"latest_partial_text"`
	LatestPartialStartOffsetMs pgtype.Int8        `json:"latest_partial_start_offset_ms"`
	LatestPartialEndOffsetMs   pgtype.Int8        `json:"latest_partial_end_offset_ms"`
	LatestPartialUpdatedAt     pgtype.Timestamptz `json:"latest_partial_updated_at"`
}

func (q *Queries) GetVoiceSessionPartialForAccount(ctx context.Context, arg GetVoiceSessionPartialForAccountParams) (GetVoiceSessionPartialForAccountRow, error) {
	row := q.db.QueryRow(ctx, getVoiceSessionPartialForAccount, arg.AccountID, arg.VoiceSessionID)
	var i GetVoiceSessionPartialForAccountRow
	err := row.Scan(
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
	)
	return i, err
}

const getVoiceTranscriptSegmentByEvent = `-- name: GetVoiceTranscriptSegmentByEvent :one
SELECT id, event_id, voice_session_id, capture_session_id, media_epoch, lane, start_offset_ms, end_offset_ms, text, normalized_text, kind, accepted_at, speaker_id, seq, superseded_at FROM voice_transcript_segments WHERE voice_session_id=$1 AND event_id=$2
`

type GetVoiceTranscriptSegmentByEventParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	EventID        string `json:"event_id"`
}

func (q *Queries) GetVoiceTranscriptSegmentByEvent(ctx context.Context, arg GetVoiceTranscriptSegmentByEventParams) (VoiceTranscriptSegment, error) {
	row := q.db.QueryRow(ctx, getVoiceTranscriptSegmentByEvent, arg.VoiceSessionID, arg.EventID)
	var i VoiceTranscriptSegment
	err := row.Scan(
		&i.ID,
		&i.EventID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.MediaEpoch,
		&i.Lane,
		&i.StartOffsetMs,
		&i.EndOffsetMs,
		&i.Text,
		&i.NormalizedText,
		&i.Kind,
		&i.AcceptedAt,
		&i.SpeakerID,
		&i.Seq,
		&i.SupersededAt,
	)
	return i, err
}

const invalidateUnauthorizedVoiceSession = `-- name: InvalidateUnauthorizedVoiceSession :one
WITH revoked AS (
  UPDATE voice_sessions voice
  SET status='closing',last_failure_code='membership_revoked',updated_at=clock_timestamp()
  WHERE voice.id=$1 AND voice.status IN ('provisioning','connected','reconnecting')
    AND NOT EXISTS (
      SELECT 1 FROM active_room_members member
      JOIN actors actor ON actor.id=member.actor_id AND actor.tenant_id=member.tenant_id
      JOIN rooms room ON room.id=member.room_id AND room.deleted_at IS NULL
      WHERE member.room_id=voice.room_id AND member.actor_id=voice.created_by_actor_id
        AND actor.kind='human' AND actor.account_id IS NOT NULL
    )
  RETURNING voice.id, voice.tenant_id, voice.room_id, voice.created_by_actor_id, voice.status, voice.provider_room_name, voice.participant_identity, voice.credential_generation, voice.last_failure_code, voice.created_at, voice.updated_at, voice.closed_at, voice.latest_partial_text, voice.latest_partial_start_offset_ms, voice.latest_partial_end_offset_ms, voice.latest_partial_updated_at, voice.last_input_started_ms, voice.last_input_ended_ms, voice.purpose, voice.auth_session_id, voice.live_agent_actor_id, voice.live_lease_until, voice.next_media_epoch
), failed_captures AS (
  UPDATE capture_sessions capture SET status='failed',updated_at=clock_timestamp()
  FROM revoked voice
  WHERE capture.voice_session_id=voice.id AND capture.status IN ('starting','recording','finalizing')
  RETURNING capture.id
), failed_epochs AS (
  UPDATE voice_media_epochs epoch
  SET desired_state='sealed',observed_state='failed',last_failure_code='membership_revoked',updated_at=clock_timestamp()
  FROM failed_captures capture WHERE epoch.capture_session_id=capture.id
)
SELECT id FROM revoked
`

func (q *Queries) InvalidateUnauthorizedVoiceSession(ctx context.Context, id string) (string, error) {
	row := q.db.QueryRow(ctx, invalidateUnauthorizedVoiceSession, id)
	err := row.Scan(&id)
	return id, err
}

const listCaptureMediaRangesForCapture = `-- name: ListCaptureMediaRangesForCapture :many
SELECT id, capture_session_id, epoch_id, kind, start_offset_ms, end_offset_ms, reason, created_at FROM capture_media_ranges
WHERE capture_session_id=$1
ORDER BY start_offset_ms,end_offset_ms,id
`

func (q *Queries) ListCaptureMediaRangesForCapture(ctx context.Context, captureSessionID string) ([]CaptureMediaRange, error) {
	rows, err := q.db.Query(ctx, listCaptureMediaRangesForCapture, captureSessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []CaptureMediaRange{}
	for rows.Next() {
		var i CaptureMediaRange
		if err := rows.Scan(
			&i.ID,
			&i.CaptureSessionID,
			&i.EpochID,
			&i.Kind,
			&i.StartOffsetMs,
			&i.EndOffsetMs,
			&i.Reason,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listUnfinishedVoiceWork = `-- name: ListUnfinishedVoiceWork :many
SELECT 'session'::text AS kind,id FROM voice_sessions WHERE status<>'closed'
UNION ALL
SELECT 'capture'::text,id FROM capture_sessions
WHERE voice_session_id IS NOT NULL AND status IN ('starting','recording','finalizing')
UNION ALL
SELECT 'stop'::text,id FROM capture_sessions
WHERE status='finalizing' AND stop_requested_at IS NOT NULL
UNION ALL
SELECT 'materialize'::text,id FROM capture_sessions
WHERE status IN ('finalizing','recovering') AND materialize_requested_at IS NOT NULL
UNION ALL
SELECT 'transcript_recovery'::text,id FROM capture_sessions
WHERE status='recovering' AND transcript_recovered_at IS NULL AND transcript_recovery_status IN ('pending','running')
UNION ALL
SELECT 'completion'::text,id FROM capture_sessions
WHERE status='finalized' AND document_version_id IS NOT NULL
  AND transcript_document_version_id IS NULL AND voice_completion_failed_at IS NULL
UNION ALL
SELECT 'staging_cleanup'::text,id FROM capture_sessions
WHERE voice_session_id IS NOT NULL AND status IN ('finalized','failed') AND staging_deleted_at IS NULL
`

type ListUnfinishedVoiceWorkRow struct {
	Kind string `json:"kind"`
	ID   string `json:"id"`
}

// Every voice session and Capture that still owes background work, by the
// kind of job that does it.
func (q *Queries) ListUnfinishedVoiceWork(ctx context.Context) ([]ListUnfinishedVoiceWorkRow, error) {
	rows, err := q.db.Query(ctx, listUnfinishedVoiceWork)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListUnfinishedVoiceWorkRow{}
	for rows.Next() {
		var i ListUnfinishedVoiceWorkRow
		if err := rows.Scan(&i.Kind, &i.ID); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceMediaEpochsForCapture = `-- name: ListVoiceMediaEpochsForCapture :many
SELECT id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at FROM voice_media_epochs
WHERE capture_session_id=$1
ORDER BY epoch_index,id
`

func (q *Queries) ListVoiceMediaEpochsForCapture(ctx context.Context, captureSessionID string) ([]VoiceMediaEpoch, error) {
	rows, err := q.db.Query(ctx, listVoiceMediaEpochsForCapture, captureSessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []VoiceMediaEpoch{}
	for rows.Next() {
		var i VoiceMediaEpoch
		if err := rows.Scan(
			&i.ID,
			&i.VoiceSessionID,
			&i.CaptureSessionID,
			&i.EpochIndex,
			&i.DesiredState,
			&i.ObservedState,
			&i.ProviderEgressID,
			&i.StagingPrefix,
			&i.PlaylistObjectKey,
			&i.FirstArchivedMs,
			&i.ArchivedThroughMs,
			&i.SegmentCount,
			&i.LastSegmentAt,
			&i.FinalEndMs,
			&i.LastFailureCode,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.SealedAt,
			&i.RecorderState,
			&i.RecorderStartedAt,
			&i.RecorderArchivedThroughMs,
			&i.RecorderFailureCode,
			&i.RecorderReportedAt,
			&i.RestartRetryAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceMediaEpochsForReconcile = `-- name: ListVoiceMediaEpochsForReconcile :many
SELECT epoch.id, epoch.voice_session_id, epoch.capture_session_id, epoch.epoch_index, epoch.desired_state, epoch.observed_state, epoch.provider_egress_id, epoch.staging_prefix, epoch.playlist_object_key, epoch.first_archived_ms, epoch.archived_through_ms, epoch.segment_count, epoch.last_segment_at, epoch.final_end_ms, epoch.last_failure_code, epoch.created_at, epoch.updated_at, epoch.sealed_at, epoch.recorder_state, epoch.recorder_started_at, epoch.recorder_archived_through_ms, epoch.recorder_failure_code, epoch.recorder_reported_at, epoch.restart_retry_at,voice.provider_room_name,voice.participant_identity,
       capture.status AS capture_status,actor.account_id,capture.stop_requested_at
FROM voice_media_epochs epoch
JOIN voice_sessions voice ON voice.id=epoch.voice_session_id
JOIN capture_sessions capture ON capture.id=epoch.capture_session_id
JOIN actors actor
  ON actor.id=capture.created_by_actor_id AND actor.tenant_id=capture.tenant_id AND actor.kind='human'
WHERE epoch.capture_session_id=$1::text
  AND (epoch.observed_state IN ('requested','active','sealing','unknown')
       OR (epoch.observed_state='failed' AND epoch.last_failure_code='egress_failed_without_media'))
  AND capture.status IN ('starting','recording','finalizing')
  AND epoch.updated_at < clock_timestamp()-interval '2 seconds'
  AND (epoch.epoch_index=0 OR epoch.first_archived_ms IS NOT NULL
       OR epoch.restart_retry_at IS NULL OR epoch.restart_retry_at<=clock_timestamp())
ORDER BY epoch.updated_at,epoch.id
LIMIT 1
`

type ListVoiceMediaEpochsForReconcileRow struct {
	ID                        string             `json:"id"`
	VoiceSessionID            string             `json:"voice_session_id"`
	CaptureSessionID          string             `json:"capture_session_id"`
	EpochIndex                int32              `json:"epoch_index"`
	DesiredState              string             `json:"desired_state"`
	ObservedState             string             `json:"observed_state"`
	ProviderEgressID          pgtype.Text        `json:"provider_egress_id"`
	StagingPrefix             string             `json:"staging_prefix"`
	PlaylistObjectKey         pgtype.Text        `json:"playlist_object_key"`
	FirstArchivedMs           pgtype.Int8        `json:"first_archived_ms"`
	ArchivedThroughMs         pgtype.Int8        `json:"archived_through_ms"`
	SegmentCount              int64              `json:"segment_count"`
	LastSegmentAt             pgtype.Timestamptz `json:"last_segment_at"`
	FinalEndMs                pgtype.Int8        `json:"final_end_ms"`
	LastFailureCode           pgtype.Text        `json:"last_failure_code"`
	CreatedAt                 pgtype.Timestamptz `json:"created_at"`
	UpdatedAt                 pgtype.Timestamptz `json:"updated_at"`
	SealedAt                  pgtype.Timestamptz `json:"sealed_at"`
	RecorderState             pgtype.Text        `json:"recorder_state"`
	RecorderStartedAt         pgtype.Timestamptz `json:"recorder_started_at"`
	RecorderArchivedThroughMs pgtype.Int8        `json:"recorder_archived_through_ms"`
	RecorderFailureCode       pgtype.Text        `json:"recorder_failure_code"`
	RecorderReportedAt        pgtype.Timestamptz `json:"recorder_reported_at"`
	RestartRetryAt            pgtype.Timestamptz `json:"restart_retry_at"`
	ProviderRoomName          string             `json:"provider_room_name"`
	ParticipantIdentity       string             `json:"participant_identity"`
	CaptureStatus             string             `json:"capture_status"`
	AccountID                 pgtype.Text        `json:"account_id"`
	StopRequestedAt           pgtype.Timestamptz `json:"stop_requested_at"`
}

func (q *Queries) ListVoiceMediaEpochsForReconcile(ctx context.Context, captureSessionID string) ([]ListVoiceMediaEpochsForReconcileRow, error) {
	rows, err := q.db.Query(ctx, listVoiceMediaEpochsForReconcile, captureSessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceMediaEpochsForReconcileRow{}
	for rows.Next() {
		var i ListVoiceMediaEpochsForReconcileRow
		if err := rows.Scan(
			&i.ID,
			&i.VoiceSessionID,
			&i.CaptureSessionID,
			&i.EpochIndex,
			&i.DesiredState,
			&i.ObservedState,
			&i.ProviderEgressID,
			&i.StagingPrefix,
			&i.PlaylistObjectKey,
			&i.FirstArchivedMs,
			&i.ArchivedThroughMs,
			&i.SegmentCount,
			&i.LastSegmentAt,
			&i.FinalEndMs,
			&i.LastFailureCode,
			&i.CreatedAt,
			&i.UpdatedAt,
			&i.SealedAt,
			&i.RecorderState,
			&i.RecorderStartedAt,
			&i.RecorderArchivedThroughMs,
			&i.RecorderFailureCode,
			&i.RecorderReportedAt,
			&i.RestartRetryAt,
			&i.ProviderRoomName,
			&i.ParticipantIdentity,
			&i.CaptureStatus,
			&i.AccountID,
			&i.StopRequestedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const listVoiceTranscriptEventsForAccount = `-- name: ListVoiceTranscriptEventsForAccount :many
SELECT segment.id,segment.event_id,segment.voice_session_id,
       coalesce(segment.capture_session_id,'')::text AS capture_session_id,
       segment.media_epoch,segment.lane,segment.start_offset_ms,segment.end_offset_ms,
       segment.text,segment.speaker_id,segment.kind,segment.accepted_at,
       segment.accepted_at::timestamptz AS updated_at,segment.seq
FROM voice_transcript_segments segment
JOIN voice_sessions voice ON voice.id=segment.voice_session_id
JOIN actors caller
  ON caller.id=voice.created_by_actor_id
 AND caller.account_id=$1::text
 AND caller.kind='human'
JOIN active_room_members membership
  ON membership.room_id=voice.room_id AND membership.actor_id=caller.id
JOIN rooms room ON room.id=voice.room_id AND room.deleted_at IS NULL
WHERE voice.id=$2::text AND segment.lane='live'
  AND (
    segment.accepted_at > $3::timestamptz OR
    (segment.accepted_at=$3::timestamptz
      AND segment.id > $4::text)
  )
ORDER BY segment.accepted_at,segment.id
LIMIT 100
`

type ListVoiceTranscriptEventsForAccountParams struct {
	AccountID      string             `json:"account_id"`
	VoiceSessionID string             `json:"voice_session_id"`
	AfterUpdatedAt pgtype.Timestamptz `json:"after_updated_at"`
	AfterID        string             `json:"after_id"`
}

type ListVoiceTranscriptEventsForAccountRow struct {
	ID               string             `json:"id"`
	EventID          string             `json:"event_id"`
	VoiceSessionID   string             `json:"voice_session_id"`
	CaptureSessionID string             `json:"capture_session_id"`
	MediaEpoch       int32              `json:"media_epoch"`
	Lane             string             `json:"lane"`
	StartOffsetMs    int64              `json:"start_offset_ms"`
	EndOffsetMs      int64              `json:"end_offset_ms"`
	Text             string             `json:"text"`
	SpeakerID        pgtype.Text        `json:"speaker_id"`
	Kind             string             `json:"kind"`
	AcceptedAt       pgtype.Timestamptz `json:"accepted_at"`
	UpdatedAt        pgtype.Timestamptz `json:"updated_at"`
	Seq              int64              `json:"seq"`
}

func (q *Queries) ListVoiceTranscriptEventsForAccount(ctx context.Context, arg ListVoiceTranscriptEventsForAccountParams) ([]ListVoiceTranscriptEventsForAccountRow, error) {
	rows, err := q.db.Query(ctx, listVoiceTranscriptEventsForAccount,
		arg.AccountID,
		arg.VoiceSessionID,
		arg.AfterUpdatedAt,
		arg.AfterID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	items := []ListVoiceTranscriptEventsForAccountRow{}
	for rows.Next() {
		var i ListVoiceTranscriptEventsForAccountRow
		if err := rows.Scan(
			&i.ID,
			&i.EventID,
			&i.VoiceSessionID,
			&i.CaptureSessionID,
			&i.MediaEpoch,
			&i.Lane,
			&i.StartOffsetMs,
			&i.EndOffsetMs,
			&i.Text,
			&i.SpeakerID,
			&i.Kind,
			&i.AcceptedAt,
			&i.UpdatedAt,
			&i.Seq,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const lockVoiceSession = `-- name: LockVoiceSession :one
SELECT id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch FROM voice_sessions WHERE id=$1 FOR NO KEY UPDATE
`

// NO KEY: commit-time foreign-key checks from children take KEY SHARE on
// this row and must not wait behind its holder. Transcript writers hold it
// until commit, which orders voice_transcript_segments.seq by commit.
func (q *Queries) LockVoiceSession(ctx context.Context, id string) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, lockVoiceSession, id)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const markStoppedVoiceTranscriptGap = `-- name: MarkStoppedVoiceTranscriptGap :exec
WITH interrupted AS (
UPDATE capture_sessions capture SET transcript_integrity_lost=true
FROM voice_sessions voice
WHERE capture.id=$1 AND capture.voice_session_id=voice.id
  AND capture.status IN ('starting','recording','finalizing')
  AND voice.last_input_started_ms IS NOT NULL
  AND voice.last_input_ended_ms >= voice.last_input_started_ms
  AND extract(epoch FROM clock_timestamp()-voice.created_at)*1000 > voice.last_input_ended_ms+250
RETURNING capture.id,greatest(coalesce(capture.transcript_start_offset_ms,0),voice.last_input_ended_ms) AS start_ms,
  floor(extract(epoch FROM clock_timestamp()-voice.created_at)*1000)::bigint AS end_ms
)
INSERT INTO voice_transcript_uncertainties(capture_session_id,event_id,start_offset_ms,end_offset_ms,reason)
SELECT id,'input-ended:' || start_ms::text,start_ms,end_ms,'input_ended' FROM interrupted WHERE end_ms>start_ms
ON CONFLICT(capture_session_id,event_id) DO UPDATE SET end_offset_ms=greatest(voice_transcript_uncertainties.end_offset_ms,EXCLUDED.end_offset_ms)
`

func (q *Queries) MarkStoppedVoiceTranscriptGap(ctx context.Context, id string) error {
	_, err := q.db.Exec(ctx, markStoppedVoiceTranscriptGap, id)
	return err
}

const markVoiceMediaEpochFailed = `-- name: MarkVoiceMediaEpochFailed :one
UPDATE voice_media_epochs
SET observed_state='failed',last_failure_code=$2,updated_at=clock_timestamp()
WHERE id=$1 AND observed_state IN ('requested','active','sealing','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type MarkVoiceMediaEpochFailedParams struct {
	ID              string      `json:"id"`
	LastFailureCode pgtype.Text `json:"last_failure_code"`
}

func (q *Queries) MarkVoiceMediaEpochFailed(ctx context.Context, arg MarkVoiceMediaEpochFailedParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, markVoiceMediaEpochFailed, arg.ID, arg.LastFailureCode)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const markVoiceMediaEpochUnknown = `-- name: MarkVoiceMediaEpochUnknown :one
UPDATE voice_media_epochs
SET observed_state='unknown',last_failure_code=$2,updated_at=clock_timestamp()
WHERE id=$1 AND observed_state IN ('requested','active','sealing','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type MarkVoiceMediaEpochUnknownParams struct {
	ID              string      `json:"id"`
	LastFailureCode pgtype.Text `json:"last_failure_code"`
}

func (q *Queries) MarkVoiceMediaEpochUnknown(ctx context.Context, arg MarkVoiceMediaEpochUnknownParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, markVoiceMediaEpochUnknown, arg.ID, arg.LastFailureCode)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const markVoiceSessionPublisherAbsent = `-- name: MarkVoiceSessionPublisherAbsent :exec
UPDATE voice_sessions
SET status='reconnecting',last_failure_code='publisher_absent',updated_at=clock_timestamp()
WHERE id=$1 AND credential_generation=$2 AND status IN ('provisioning','connected','reconnecting')
`

type MarkVoiceSessionPublisherAbsentParams struct {
	ID                   string `json:"id"`
	CredentialGeneration int64  `json:"credential_generation"`
}

func (q *Queries) MarkVoiceSessionPublisherAbsent(ctx context.Context, arg MarkVoiceSessionPublisherAbsentParams) error {
	_, err := q.db.Exec(ctx, markVoiceSessionPublisherAbsent, arg.ID, arg.CredentialGeneration)
	return err
}

const markVoiceSessionReconnecting = `-- name: MarkVoiceSessionReconnecting :one
UPDATE voice_sessions
SET status='reconnecting',last_failure_code=$2,updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting')
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

type MarkVoiceSessionReconnectingParams struct {
	ID              string      `json:"id"`
	LastFailureCode pgtype.Text `json:"last_failure_code"`
}

func (q *Queries) MarkVoiceSessionReconnecting(ctx context.Context, arg MarkVoiceSessionReconnectingParams) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, markVoiceSessionReconnecting, arg.ID, arg.LastFailureCode)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const markVoiceStagingDeleted = `-- name: MarkVoiceStagingDeleted :exec
UPDATE capture_sessions SET staging_deleted_at=clock_timestamp()
WHERE id=$1 AND staging_deleted_at IS NULL
`

func (q *Queries) MarkVoiceStagingDeleted(ctx context.Context, id string) error {
	_, err := q.db.Exec(ctx, markVoiceStagingDeleted, id)
	return err
}

const observeVoiceMediaSegmentProgress = `-- name: ObserveVoiceMediaSegmentProgress :one
UPDATE voice_media_epochs
SET segment_count=greatest(segment_count,$1::bigint),
    last_segment_at=CASE
      WHEN $1::bigint > segment_count THEN clock_timestamp()
      ELSE last_segment_at
    END,
    updated_at=clock_timestamp()
WHERE id=$2::text AND observed_state IN ('requested','active','sealing','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type ObserveVoiceMediaSegmentProgressParams struct {
	SegmentCount int64  `json:"segment_count"`
	ID           string `json:"id"`
}

func (q *Queries) ObserveVoiceMediaSegmentProgress(ctx context.Context, arg ObserveVoiceMediaSegmentProgressParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, observeVoiceMediaSegmentProgress, arg.SegmentCount, arg.ID)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const recordVoiceInputBoundary = `-- name: RecordVoiceInputBoundary :exec
WITH previous_input AS (
  SELECT id,last_input_started_ms,last_input_ended_ms
  FROM voice_sessions
  WHERE id=$3::text
  FOR NO KEY UPDATE
), interrupted_capture AS (
  UPDATE capture_sessions capture
  SET transcript_integrity_lost=true
  FROM previous_input previous
  WHERE capture.voice_session_id=previous.id
    AND capture.status IN ('starting','recording','finalizing')
    AND $1::text='track_started'
    AND $2::bigint > coalesce(previous.last_input_started_ms,-1)
    AND previous.last_input_started_ms IS NOT NULL
    AND (
      previous.last_input_started_ms > coalesce(previous.last_input_ended_ms,-1) OR
      $2::bigint > greatest(coalesce(previous.last_input_ended_ms,$2::bigint),
        coalesce(capture.transcript_start_offset_ms,$2::bigint)) + 250
    )
  RETURNING capture.id,
    greatest(coalesce(capture.transcript_start_offset_ms,0),
      CASE WHEN previous.last_input_started_ms > coalesce(previous.last_input_ended_ms,-1)
      THEN coalesce((SELECT max(coverage.end_offset_ms) FROM capture_transcript_coverage coverage
        WHERE coverage.session_id=capture.id AND coverage.end_offset_ms<=$2::bigint),previous.last_input_started_ms)
      ELSE previous.last_input_ended_ms END) AS uncertainty_start
), uncertainty AS (
  INSERT INTO voice_transcript_uncertainties(capture_session_id,event_id,start_offset_ms,end_offset_ms,reason)
  SELECT id,'track-start:' || $2::bigint::text,uncertainty_start,$2::bigint,'track_interruption'
  FROM interrupted_capture WHERE uncertainty_start<$2::bigint
  ON CONFLICT(capture_session_id,event_id) DO NOTHING
)
UPDATE voice_sessions voice
SET last_input_started_ms=CASE WHEN $1::text='track_started'
      THEN greatest(coalesce(voice.last_input_started_ms,0),$2::bigint) ELSE voice.last_input_started_ms END,
    last_input_ended_ms=CASE WHEN $1::text='track_ended'
      THEN greatest(coalesce(voice.last_input_ended_ms,0),$2::bigint) ELSE voice.last_input_ended_ms END
FROM previous_input previous
WHERE voice.id=previous.id
`

type RecordVoiceInputBoundaryParams struct {
	Kind           string `json:"kind"`
	OffsetMs       int64  `json:"offset_ms"`
	VoiceSessionID string `json:"voice_session_id"`
}

func (q *Queries) RecordVoiceInputBoundary(ctx context.Context, arg RecordVoiceInputBoundaryParams) error {
	_, err := q.db.Exec(ctx, recordVoiceInputBoundary, arg.Kind, arg.OffsetMs, arg.VoiceSessionID)
	return err
}

const releaseVoiceMediaMaterialization = `-- name: ReleaseVoiceMediaMaterialization :exec
UPDATE capture_sessions
SET materialize_retry_at=clock_timestamp()+$1::interval,
    materialize_attempts=CASE WHEN $2::boolean
      THEN greatest(materialize_attempts-1,0) ELSE materialize_attempts END
WHERE id=$3::text
`

type ReleaseVoiceMediaMaterializationParams struct {
	RetryDelay    pgtype.Interval `json:"retry_delay"`
	RefundAttempt bool            `json:"refund_attempt"`
	ID            string          `json:"id"`
}

// Holds the next attempt back by the retry delay. A materialization that waits
// for the transcript returns the attempt it took, so a long transcript wait
// does not spend the failure budget.
func (q *Queries) ReleaseVoiceMediaMaterialization(ctx context.Context, arg ReleaseVoiceMediaMaterializationParams) error {
	_, err := q.db.Exec(ctx, releaseVoiceMediaMaterialization, arg.RetryDelay, arg.RefundAttempt, arg.ID)
	return err
}

const requestSealVoiceMediaEpoch = `-- name: RequestSealVoiceMediaEpoch :one
UPDATE voice_media_epochs
SET desired_state='sealed',observed_state=CASE WHEN observed_state='active' THEN 'sealing' ELSE observed_state END,
    updated_at=clock_timestamp()
WHERE id=$1 AND desired_state='active' AND observed_state IN ('requested','active','sealing','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

func (q *Queries) RequestSealVoiceMediaEpoch(ctx context.Context, id string) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, requestSealVoiceMediaEpoch, id)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const requestVoiceCaptureMaterialization = `-- name: RequestVoiceCaptureMaterialization :exec
UPDATE capture_sessions SET materialize_requested_at=coalesce(materialize_requested_at,clock_timestamp())
WHERE id=$1
`

func (q *Queries) RequestVoiceCaptureMaterialization(ctx context.Context, id string) error {
	_, err := q.db.Exec(ctx, requestVoiceCaptureMaterialization, id)
	return err
}

const requestVoiceCaptureStop = `-- name: RequestVoiceCaptureStop :one
UPDATE capture_sessions SET stop_requested_at=clock_timestamp()
WHERE id=$1 AND stop_requested_at IS NULL
RETURNING id, tenant_id, room_id, created_by_actor_id, status, created_at, updated_at, transcript_start_offset_ms, transcript_end_offset_ms, document_id, document_version_id, transcript_document_id, transcript_document_version_id, voice_session_id, transcript_integrity_lost, source_audio_document_id, source_audio_document_version_id, transcript_recovered_at, requested_transcript_start_offset_ms, voice_completion_attempts, voice_completion_failed_at, voice_completion_failure_code, staging_deleted_at, stop_requested_at, materialize_requested_at, materialize_attempts, materialize_retry_at, transcript_recovery_status, transcript_recovery_progress_ms, transcript_recovery_total_ms, transcript_recovery_failures, transcript_recovery_failure_code, transcript_recovery_retry_at, hidden_at, quick_notes_state, quick_notes
`

// Records the first Stop's commit time: the stop intent the final media end
// is cut at. A Capture that already has one is left alone.
func (q *Queries) RequestVoiceCaptureStop(ctx context.Context, id string) (CaptureSession, error) {
	row := q.db.QueryRow(ctx, requestVoiceCaptureStop, id)
	var i CaptureSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const requestVoiceSessionClose = `-- name: RequestVoiceSessionClose :one
UPDATE voice_sessions SET status='closing',updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

func (q *Queries) RequestVoiceSessionClose(ctx context.Context, id string) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, requestVoiceSessionClose, id)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const sealVoiceMediaEpoch = `-- name: SealVoiceMediaEpoch :one
UPDATE voice_media_epochs
SET desired_state='sealed',observed_state='available',playlist_object_key=$2,
    archived_through_ms=$3,final_end_ms=$3,sealed_at=clock_timestamp(),updated_at=clock_timestamp()
WHERE id=$1 AND observed_state IN ('requested','active','sealing','unknown')
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type SealVoiceMediaEpochParams struct {
	ID                string      `json:"id"`
	PlaylistObjectKey pgtype.Text `json:"playlist_object_key"`
	ArchivedThroughMs pgtype.Int8 `json:"archived_through_ms"`
}

func (q *Queries) SealVoiceMediaEpoch(ctx context.Context, arg SealVoiceMediaEpochParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, sealVoiceMediaEpoch, arg.ID, arg.PlaylistObjectKey, arg.ArchivedThroughMs)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const sealVoiceMediaEpochAtBoundary = `-- name: SealVoiceMediaEpochAtBoundary :one
UPDATE voice_media_epochs
SET desired_state='sealed',observed_state='available',playlist_object_key=$2,
    archived_through_ms=$3,final_end_ms=$4,sealed_at=clock_timestamp(),updated_at=clock_timestamp()
WHERE id=$1
  AND observed_state IN ('requested','active','sealing','unknown','available')
  AND $4::bigint > coalesce(first_archived_ms,0)
  AND $4::bigint <= $3::bigint
RETURNING id, voice_session_id, capture_session_id, epoch_index, desired_state, observed_state, provider_egress_id, staging_prefix, playlist_object_key, first_archived_ms, archived_through_ms, segment_count, last_segment_at, final_end_ms, last_failure_code, created_at, updated_at, sealed_at, recorder_state, recorder_started_at, recorder_archived_through_ms, recorder_failure_code, recorder_reported_at, restart_retry_at
`

type SealVoiceMediaEpochAtBoundaryParams struct {
	ID                string      `json:"id"`
	PlaylistObjectKey pgtype.Text `json:"playlist_object_key"`
	ArchivedThroughMs pgtype.Int8 `json:"archived_through_ms"`
	FinalEndMs        pgtype.Int8 `json:"final_end_ms"`
}

func (q *Queries) SealVoiceMediaEpochAtBoundary(ctx context.Context, arg SealVoiceMediaEpochAtBoundaryParams) (VoiceMediaEpoch, error) {
	row := q.db.QueryRow(ctx, sealVoiceMediaEpochAtBoundary,
		arg.ID,
		arg.PlaylistObjectKey,
		arg.ArchivedThroughMs,
		arg.FinalEndMs,
	)
	var i VoiceMediaEpoch
	err := row.Scan(
		&i.ID,
		&i.VoiceSessionID,
		&i.CaptureSessionID,
		&i.EpochIndex,
		&i.DesiredState,
		&i.ObservedState,
		&i.ProviderEgressID,
		&i.StagingPrefix,
		&i.PlaylistObjectKey,
		&i.FirstArchivedMs,
		&i.ArchivedThroughMs,
		&i.SegmentCount,
		&i.LastSegmentAt,
		&i.FinalEndMs,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.SealedAt,
		&i.RecorderState,
		&i.RecorderStartedAt,
		&i.RecorderArchivedThroughMs,
		&i.RecorderFailureCode,
		&i.RecorderReportedAt,
		&i.RestartRetryAt,
	)
	return i, err
}

const transitionLiveKitCaptureStatus = `-- name: TransitionLiveKitCaptureStatus :one
UPDATE capture_sessions
SET status=$1::text,updated_at=clock_timestamp()
WHERE id=$2::text
  AND (
    (status='starting' AND $1::text IN ('recording','finalizing','failed')) OR
    (status='recording' AND $1::text IN ('finalizing','failed')) OR
    (status='finalizing' AND $1::text='failed') OR
    status=$1::text
  )
RETURNING id, tenant_id, room_id, created_by_actor_id, status, created_at, updated_at, transcript_start_offset_ms, transcript_end_offset_ms, document_id, document_version_id, transcript_document_id, transcript_document_version_id, voice_session_id, transcript_integrity_lost, source_audio_document_id, source_audio_document_version_id, transcript_recovered_at, requested_transcript_start_offset_ms, voice_completion_attempts, voice_completion_failed_at, voice_completion_failure_code, staging_deleted_at, stop_requested_at, materialize_requested_at, materialize_attempts, materialize_retry_at, transcript_recovery_status, transcript_recovery_progress_ms, transcript_recovery_total_ms, transcript_recovery_failures, transcript_recovery_failure_code, transcript_recovery_retry_at, hidden_at, quick_notes_state, quick_notes
`

type TransitionLiveKitCaptureStatusParams struct {
	Status string `json:"status"`
	ID     string `json:"id"`
}

func (q *Queries) TransitionLiveKitCaptureStatus(ctx context.Context, arg TransitionLiveKitCaptureStatusParams) (CaptureSession, error) {
	row := q.db.QueryRow(ctx, transitionLiveKitCaptureStatus, arg.Status, arg.ID)
	var i CaptureSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.TranscriptStartOffsetMs,
		&i.TranscriptEndOffsetMs,
		&i.DocumentID,
		&i.DocumentVersionID,
		&i.TranscriptDocumentID,
		&i.TranscriptDocumentVersionID,
		&i.VoiceSessionID,
		&i.TranscriptIntegrityLost,
		&i.SourceAudioDocumentID,
		&i.SourceAudioDocumentVersionID,
		&i.TranscriptRecoveredAt,
		&i.RequestedTranscriptStartOffsetMs,
		&i.VoiceCompletionAttempts,
		&i.VoiceCompletionFailedAt,
		&i.VoiceCompletionFailureCode,
		&i.StagingDeletedAt,
		&i.StopRequestedAt,
		&i.MaterializeRequestedAt,
		&i.MaterializeAttempts,
		&i.MaterializeRetryAt,
		&i.TranscriptRecoveryStatus,
		&i.TranscriptRecoveryProgressMs,
		&i.TranscriptRecoveryTotalMs,
		&i.TranscriptRecoveryFailures,
		&i.TranscriptRecoveryFailureCode,
		&i.TranscriptRecoveryRetryAt,
		&i.HiddenAt,
		&i.QuickNotesState,
		&i.QuickNotes,
	)
	return i, err
}

const updateVoiceSessionPartialTranscript = `-- name: UpdateVoiceSessionPartialTranscript :one
UPDATE voice_sessions
SET latest_partial_text=$2,latest_partial_start_offset_ms=$3,
    latest_partial_end_offset_ms=$4,latest_partial_updated_at=clock_timestamp(),updated_at=clock_timestamp()
WHERE id=$1 AND status IN ('provisioning','connected','reconnecting','closing')
RETURNING id, tenant_id, room_id, created_by_actor_id, status, provider_room_name, participant_identity, credential_generation, last_failure_code, created_at, updated_at, closed_at, latest_partial_text, latest_partial_start_offset_ms, latest_partial_end_offset_ms, latest_partial_updated_at, last_input_started_ms, last_input_ended_ms, purpose, auth_session_id, live_agent_actor_id, live_lease_until, next_media_epoch
`

type UpdateVoiceSessionPartialTranscriptParams struct {
	ID                         string      `json:"id"`
	LatestPartialText          pgtype.Text `json:"latest_partial_text"`
	LatestPartialStartOffsetMs pgtype.Int8 `json:"latest_partial_start_offset_ms"`
	LatestPartialEndOffsetMs   pgtype.Int8 `json:"latest_partial_end_offset_ms"`
}

func (q *Queries) UpdateVoiceSessionPartialTranscript(ctx context.Context, arg UpdateVoiceSessionPartialTranscriptParams) (VoiceSession, error) {
	row := q.db.QueryRow(ctx, updateVoiceSessionPartialTranscript,
		arg.ID,
		arg.LatestPartialText,
		arg.LatestPartialStartOffsetMs,
		arg.LatestPartialEndOffsetMs,
	)
	var i VoiceSession
	err := row.Scan(
		&i.ID,
		&i.TenantID,
		&i.RoomID,
		&i.CreatedByActorID,
		&i.Status,
		&i.ProviderRoomName,
		&i.ParticipantIdentity,
		&i.CredentialGeneration,
		&i.LastFailureCode,
		&i.CreatedAt,
		&i.UpdatedAt,
		&i.ClosedAt,
		&i.LatestPartialText,
		&i.LatestPartialStartOffsetMs,
		&i.LatestPartialEndOffsetMs,
		&i.LatestPartialUpdatedAt,
		&i.LastInputStartedMs,
		&i.LastInputEndedMs,
		&i.Purpose,
		&i.AuthSessionID,
		&i.LiveAgentActorID,
		&i.LiveLeaseUntil,
		&i.NextMediaEpoch,
	)
	return i, err
}

const voiceCaptureBelongsToAuthSession = `-- name: VoiceCaptureBelongsToAuthSession :one
SELECT EXISTS (SELECT 1 FROM capture_sessions capture
  JOIN voice_sessions voice ON voice.id=capture.voice_session_id
  WHERE capture.id=$1::text AND voice.auth_session_id=$2::text)
`

type VoiceCaptureBelongsToAuthSessionParams struct {
	CaptureSessionID string `json:"capture_session_id"`
	AuthSessionID    string `json:"auth_session_id"`
}

func (q *Queries) VoiceCaptureBelongsToAuthSession(ctx context.Context, arg VoiceCaptureBelongsToAuthSessionParams) (bool, error) {
	row := q.db.QueryRow(ctx, voiceCaptureBelongsToAuthSession, arg.CaptureSessionID, arg.AuthSessionID)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const voiceEpochReconciliationDueIn = `-- name: VoiceEpochReconciliationDueIn :one
SELECT coalesce(extract(epoch FROM min(greatest(epoch.updated_at+interval '2 seconds',
    CASE WHEN epoch.epoch_index>0 AND epoch.first_archived_ms IS NULL THEN epoch.restart_retry_at END
    ))-clock_timestamp()),'Infinity')::float8 AS wait_seconds
FROM voice_media_epochs epoch
JOIN capture_sessions capture ON capture.id=epoch.capture_session_id
JOIN actors actor
  ON actor.id=capture.created_by_actor_id AND actor.tenant_id=capture.tenant_id AND actor.kind='human'
WHERE epoch.capture_session_id=$1
  AND (epoch.observed_state IN ('requested','active','sealing','unknown')
       OR (epoch.observed_state='failed' AND epoch.last_failure_code='egress_failed_without_media'))
  AND capture.status IN ('starting','recording','finalizing')
`

// Seconds until ListVoiceMediaEpochsForReconcile returns one of the Capture's
// epochs; a recovery epoch also waits out its delayed recorder restart.
func (q *Queries) VoiceEpochReconciliationDueIn(ctx context.Context, captureSessionID string) (float64, error) {
	row := q.db.QueryRow(ctx, voiceEpochReconciliationDueIn, captureSessionID)
	var wait_seconds float64
	err := row.Scan(&wait_seconds)
	return wait_seconds, err
}

const voiceMediaMaterializationDueIn = `-- name: VoiceMediaMaterializationDueIn :one
SELECT coalesce(extract(epoch FROM (
    SELECT materialize_retry_at-clock_timestamp() FROM capture_sessions
    WHERE id=$1 AND materialize_requested_at IS NOT NULL AND materialize_retry_at IS NOT NULL
      AND (status='finalizing' OR (status='recovering' AND transcript_recovered_at IS NOT NULL))
  )),'Infinity')::float8 AS wait_seconds
`

// Seconds until ClaimVoiceMediaMaterialization can take the Capture; Infinity
// when it is settled or not ready.
func (q *Queries) VoiceMediaMaterializationDueIn(ctx context.Context, id string) (float64, error) {
	row := q.db.QueryRow(ctx, voiceMediaMaterializationDueIn, id)
	var wait_seconds float64
	err := row.Scan(&wait_seconds)
	return wait_seconds, err
}

const voiceSessionBelongsToAuthSession = `-- name: VoiceSessionBelongsToAuthSession :one
SELECT EXISTS (SELECT 1 FROM voice_sessions
  WHERE id=$1::text AND auth_session_id=$2::text)
`

type VoiceSessionBelongsToAuthSessionParams struct {
	VoiceSessionID string `json:"voice_session_id"`
	AuthSessionID  string `json:"auth_session_id"`
}

func (q *Queries) VoiceSessionBelongsToAuthSession(ctx context.Context, arg VoiceSessionBelongsToAuthSessionParams) (bool, error) {
	row := q.db.QueryRow(ctx, voiceSessionBelongsToAuthSession, arg.VoiceSessionID, arg.AuthSessionID)
	var exists bool
	err := row.Scan(&exists)
	return exists, err
}

const voiceSessionReconcileDueIn = `-- name: VoiceSessionReconcileDueIn :one
SELECT coalesce(extract(epoch FROM min(updated_at+CASE
    WHEN last_failure_code='publisher_absent' AND status<>'closing' THEN interval '60 seconds'
    ELSE $1::interval
  END)-clock_timestamp()),'Infinity')::float8 AS wait_seconds
FROM voice_sessions
WHERE id=$2::text AND status IN ('provisioning','connected','reconnecting','closing')
`

type VoiceSessionReconcileDueInParams struct {
	MinAge pgtype.Interval `json:"min_age"`
	ID     string          `json:"id"`
}

// Seconds until ClaimVoiceSessionReconcile can take the session; Infinity
// once it is closed.
func (q *Queries) VoiceSessionReconcileDueIn(ctx context.Context, arg VoiceSessionReconcileDueInParams) (float64, error) {
	row := q.db.QueryRow(ctx, voiceSessionReconcileDueIn, arg.MinAge, arg.ID)
	var wait_seconds float64
	err := row.Scan(&wait_seconds)
	return wait_seconds, err
}

const voiceStagingCleanupReady = `-- name: VoiceStagingCleanupReady :one
SELECT EXISTS (
  SELECT 1 FROM capture_sessions capture
  WHERE capture.id=$1 AND capture.status IN ('finalized','failed') AND capture.staging_deleted_at IS NULL
    AND NOT EXISTS (SELECT 1 FROM voice_media_epochs epoch WHERE epoch.capture_session_id=capture.id
      AND epoch.observed_state IN ('requested','active','sealing','unknown'))
)::boolean AS ready
`

// Reports whether the Capture ended and no recorder can still write its
// staging; a Capture whose staging is already gone is not ready.
func (q *Queries) VoiceStagingCleanupReady(ctx context.Context, id string) (bool, error) {
	row := q.db.QueryRow(ctx, voiceStagingCleanupReady, id)
	var ready bool
	err := row.Scan(&ready)
	return ready, err
}