// Package codeindex builds and queries a pgvector-backed code index keyed by
// (workspace, commit). A background job (BuildRunner) embeds git-tracked file
// chunks; the Search path runs cosine-KNN scoped to the latest completed run.
// When no embedding endpoint is configured the whole feature is disabled with a
// typed error (callers degrade to keyword discovery via fs/grep).
package codeindex

import (
	"time"

	"github.com/google/uuid"

	"github.com/yan1h/agent-coding-workflow/internal/jobs"
)

// JobTypeBuild is the jobs.JobType for an event-driven index build.
const JobTypeBuild jobs.JobType = "codeindex.build"

// Run status values mirror the code_index_runs.status CHECK constraint.
const (
	StatusPending   = "pending"
	StatusRunning   = "running"
	StatusCompleted = "completed"
	StatusFailed    = "failed"
	StatusStale     = "stale"
)

// Run mirrors a code_index_runs row.
type Run struct {
	ID                  uuid.UUID
	WorkspaceID         uuid.UUID
	WorktreeID          *uuid.UUID
	Branch              string
	CommitSHA           string
	Status              string
	EmbeddingEndpointID *uuid.UUID
	EmbeddingModel      string
	Dims                int
	FilesIndexed        int
	ChunksIndexed       int
	Error               *string
	CreatedAt           time.Time
}

// Chunk is one embeddable line window produced by the Chunker.
type Chunk struct {
	StartLine  int
	EndLine    int
	Lang       string
	Content    string
	ContentSHA []byte // sha256 of Content; enables incremental re-embed
}

// Snippet is a ranked search result returned to callers (MCP search_code).
type Snippet struct {
	FilePath  string
	StartLine int
	EndLine   int
	Content   string
	Score     float32 // cosine similarity in [0,1]; higher is closer
	CommitSHA string
}

// SearchQuery parameterizes a code search.
type SearchQuery struct {
	Text       string
	TopK       int
	PathPrefix string
	Lang       string
}

// buildPayload is the jobs payload for JobTypeBuild.
type buildPayload struct {
	RunID uuid.UUID `json:"run_id"`
}
