/**
 * ML Pipeline Service
 * Manages ML model registry, training pipelines, and inference
 */

import { Context } from '../types/context'

export interface MLModel {
  id: string
  name: string
  version: string
  framework: string
  metadata: Record<string, any>
  artifactPath?: string
  createdAt: Date
  updatedAt: Date
}

export async function getModels(context: Context): Promise<MLModel[]> {
  const db = context.db
  const result = await db.query('SELECT * FROM ml_models ORDER BY created_at DESC')
  return result.rows.map(mapModel)
}

export async function getModel(context: Context, id: string): Promise<MLModel> {
  const db = context.db
  const result = await db.query('SELECT * FROM ml_models WHERE id = $1', [id])

  if (result.rows.length === 0) {
    throw new Error('Model not found')
  }

  return mapModel(result.rows[0])
}

export async function createModel(
  context: Context,
  input: {
    name: string
    version: string
    framework: string
    metadata?: Record<string, any>
    artifactPath?: string
  }
): Promise<MLModel> {
  const db = context.db
  const result = await db.query(
    `INSERT INTO ml_models (name, version, framework, metadata, artifact_path)
     VALUES ($1, $2, $3, $4, $5)
     RETURNING *`,
    [
      input.name,
      input.version,
      input.framework,
      JSON.stringify(input.metadata || {}),
      input.artifactPath || null,
    ]
  )

  return mapModel(result.rows[0])
}

function mapModel(row: any): MLModel {
  return {
    id: row.id,
    name: row.name,
    version: row.version,
    framework: row.framework,
    metadata: typeof row.metadata === 'string' ? JSON.parse(row.metadata) : (row.metadata || {}),
    artifactPath: row.artifact_path,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  }
}
