
export interface AppConfig {
  version: string
  project_key: string
  semantic_model_id: string
  max_rows_per_query: number
  agent_recursion_limit: number
  sources_records_limit: number
  artifacts_records_limit: number
}


export type AttributeType = 'COLUMN' | 'EXPRESSION'
export type DistinctValuesHandlingMode = 'NONE' | 'MANUAL' | 'AUTO_INDEX'

export interface Attribute {
  name: string
  description?: string
  dssType?: string
  type: AttributeType
  column?: string
  pseudoSQLExpression?: string
  distinctValuesHandlingMode?: DistinctValuesHandlingMode
  manualValues?: string[]
  indexDistinctValues?: boolean
  resolveInUserRequests?: boolean
  llmInstructions?: string
  sqlGenerationConfig?: Record<string, unknown>
}

export interface Metric {
  name: string
  description?: string
  pseudoSQLExpression: string
  llmInstructions?: string
  created?: NiceVersionTag
}

export interface Filter {
  name: string
  description?: string
  pseudoSQLExpression: string
  llmInstructions?: string
  created?: NiceVersionTag
}

export interface Key {
  attributes: string[]
}

export interface ForeignKey {
  referencedEntity: string
  key: Key
}

export interface EntityClass {
  name: string
  description?: string
  tags: string[]
  type: 'TABLE' | 'DATASET'
  datasetRef?: string
  connection?: string
  catalog?: string
  schema?: string
  table?: string
  attributes: Attribute[]
  metrics: Metric[]
  filters: Filter[]
  primaryKey: Key
  foreignKeys: ForeignKey[]
}

export interface Relationship {
  name?: string
  description?: string
  firstEntity: string
  secondEntity: string
  pseudoSQLExpression?: string
}

export interface SemanticModelSpec {
  entities: EntityClass[]
  relationships: Relationship[]
}

export interface VersionTagUser {
  login?: string
  displayName?: string
}

export interface VersionTag {
  lastModifiedOn?: number
  lastModifiedBy?: VersionTagUser
  version?: number
}

export interface NiceVersionTag {
  on?: string
  by?: string
  version?: number
}

// =============================================================================
// Semantic Model
// =============================================================================

export interface SemanticModel {
  id: string
  projectKey: string
  name: string
  description?: string
  shortDesc?: string
  activeVersionId?: string
  versionTag?: VersionTag
  creationTag?: VersionTag
  tags: string[]
  customFields: Record<string, unknown>
  checklists: Record<string, unknown>
  versions: SemanticModelVersion[]
}

// =============================================================================
// Version
// =============================================================================

export interface SemanticModelVersion {
  id: string
  description?: string
  created?: NiceVersionTag
  entities: EntityClass[]
  relationships: Relationship[]
  goldenQueries: GoldenQuery[]
  // vocabularyTermIds is stored in sqlGenerationConfig for DSS persistence
  vocabularyTermIds?: string[]
  glossaryBindings: GlossaryBinding[]
  glossaryTerms: GlossaryTerm[]
  indexingSettings?: Record<string, unknown>
  privateEditorData: Record<string, unknown>
  sqlGenerationConfig?: Record<string, unknown>
}

export interface VersionCreate {
  fromVersion?: string
  version?: Partial<SemanticModelVersion>
}

export interface GoldenQueryInput {
  name: string
  description?: string
  question: string
  generatedSql: string
  created?: NiceVersionTag
}

export interface VersionUpdate {
  version: Partial<SemanticModelVersion>
}

export interface IndexingStatus {
  hasResult?: boolean
  alive?: boolean
  aborted?: boolean
  jobId?: string
  jobDisplayName?: string
  runningTime?: number
  progress?: Record<string, unknown> | null
}

// =============================================================================
// Golden Query
// =============================================================================

export interface GoldenQuery {
  name: string
  description?: string
  question: string
  generatedSql: string
  created?: NiceVersionTag
}


// =============================================================================
// Playground
// =============================================================================

export interface PlaygroundFullRequest {
  semantic_model_id: string
  version_id?: string
  llm_id?: string
  embedding_llm_id?: string
  max_rows_per_query?: number
  agent_recursion_limit?: number
  sources_records_limit?: number
  artifacts_records_limit?: number
  question: string
}

export interface TermCorrection {
  original: string
  resolved: string
  entity_id: string
  attribute: string
  score: number
  match_type: 'exact' | 'fuzzy' | 'semantic'
  source: 'index' | 'glossary'
  glossary_term_id?: string
  llm_inferred?: boolean // True if LLM translated the term before matching
  // Glossary-specific: what the term maps to
  mapping_type?: 'attribute' | 'metric' | 'filter'
  mapping_name?: string
}

// Value corrections from resolve_values tool
export interface ValueCorrection {
  original: string
  resolved: string
  entity_id: string
  attribute: string
  score: number
  match_type: 'exact' | 'fuzzy' | 'semantic'
  llm_inferred?: boolean // True if LLM translated the term before matching
}

// Glossary term used during query (from bound terms)
export interface GlossaryTermUsed {
  term: string
  description?: string
  synonyms?: string[]
  entity_id?: string
  entity_name?: string
  target_type?: BindingTargetType
  target_id?: string
  target_name?: string
  is_primary?: boolean
}

// Agent tool compatibility - Sources
export interface SourceItem {
  type: 'INFO' | 'GENERATED_SQL_QUERY' | 'RECORDS' | 'ERROR'
  textSnippet?: string
  performedQuery?: string
  records?: {
    columns: string[]
    data: unknown[][]
  }
  truncated?: boolean
  total_rows?: number
}

export interface Sources {
  toolCallDescription: string
  items: SourceItem[]
}

// Agent tool compatibility - Artifacts
export interface ArtifactPart {
  type: string
  records?: {
    columns: string[]
    data: unknown[][]
  }
}

export interface Artifact {
  name: string
  description: string
  parts: ArtifactPart[]
}

export interface PlaygroundFullResponse {
  // Whether SQL was executed successfully
  success: boolean
  // Error message if success=false
  error?: string
  // Agent's natural language response
  response?: string
  // Value corrections and glossary terms used
  corrections?: ValueCorrection[]
  glossary_terms_used?: GlossaryTermUsed[]
  // Agent tool compatibility
  sources?: Sources
  artifacts?: Artifact[]
  trace?: Record<string, any>
  // Timing
  duration_ms?: number
  // For golden query saving
  sql?: string
}

// =============================================================================
// DSS Resources
// =============================================================================

export interface DSSProject {
  key: string
  name: string
}

export interface DSSDataset {
  name: string
  type: string
  schema: { name: string; type: string }[]
}

export interface DSSColumn {
  name: string
  type: string
  nullable?: boolean
  comment?: string // Column description from DSS
}

export interface DSSDatasetSchema {
  description: string // Dataset description from metadata
  label: string // Dataset label from metadata
  columns: DSSColumn[]
}

export interface DSSLLM {
  id: string
  label: string
  type: string
  connection?: string | null
}

// =============================================================================
// Auto-Generation
// =============================================================================

export type AutogenStatus = 'completed' | 'failed'

export interface CoverageReport {
  total_columns: number
  used_columns: number
  unassigned_columns: string[]
  shared_columns: string[]
  shared_details: Record<string, string[]>
}

export interface AutogenGenerateRequest {
  project_key: string
  dataset_name: string
  llm_id: string
  user_instructions?: string
}

export interface AutogenModelResponse {
  status: AutogenStatus
  model?: SemanticModelSpec
  coverage?: CoverageReport
  warnings: string[]
  error?: string
}

// =============================================================================
// Glossary
// =============================================================================

export type GlossaryTermSource = 'MANUAL' | 'EXTRACTED'
export interface GlossaryTerm {
  id: string
  term: string
  description?: string
  source: GlossaryTermSource
  userModified?: boolean
  synonyms: string[]
  created?: NiceVersionTag
  modified?: NiceVersionTag
  privateEditorData?: Record<string, unknown>
}

export interface GlossaryTermCreate {
  id?: string
  term: string
  description?: string
  source?: GlossaryTermSource
  synonyms?: string[]
  userModified?: boolean
  privateEditorData?: Record<string, unknown>
}

export interface GlossaryTermUpdate {
  term?: string
  description?: string
  source?: GlossaryTermSource
  synonyms?: string[]
  userModified?: boolean
  privateEditorData?: Record<string, unknown>
}

// =============================================================================
// Glossary Bindings (version-level)
// =============================================================================

export type BindingTargetType = 'ENTITY_CLASS' | 'ATTRIBUTE' | 'METRIC' | 'FILTER'

export interface GlossaryBinding {
  termId: string
  targetEntityClass: string
  targetType: BindingTargetType
  targetName?: string
  created?: NiceVersionTag
}

export interface GlossaryBindingCreate {
  termId: string
  targetEntityClass: string
  targetType: BindingTargetType
  targetName?: string
}

export interface BindingSuggestion {
  termId: string
  targetEntityClass: string
  targetType: BindingTargetType
  targetName?: string
  reason?: string
}

export interface GlossaryExtractionRequest {
  llm_id?: string
  max_chunks?: number
  chunk_size?: number
  chunk_overlap?: number
  spec?: SemanticModelSpec
  terms?: GlossaryTerm[]
}

export interface ExtractedTermData {
  term: string
  description?: string
  synonyms?: string[]
  privateEditorData?: Record<string, unknown>
}

export interface GlossaryConflict {
  existing_term: GlossaryTerm
  extracted_term: ExtractedTermData
}

export interface GlossaryExtractionResponse {
  documentName: string
  sectionsProcessed: number
  termsCreated: GlossaryTerm[]
  termsUpdated: GlossaryTerm[]
  conflicts: GlossaryConflict[]
}
