import type { TrainingJob, TrainingConfig, DatasetStats } from './types'

// ============================================================================
// MOCK DATA (Replace with real API calls)
// ============================================================================

export const MOCK_JOBS: TrainingJob[] = [
  {
    id: 'job-1',
    name: 'Zeugnis-RAG v2.1',
    model_type: 'zeugnis',
    status: 'training',
    progress: 67,
    current_epoch: 7,
    total_epochs: 10,
    loss: 0.234,
    val_loss: 0.289,
    learning_rate: 0.00002,
    documents_processed: 423,
    total_documents: 632,
    started_at: new Date(Date.now() - 3600000).toISOString(),
    estimated_completion: new Date(Date.now() + 1800000).toISOString(),
    error_message: null,
    metrics: {
      precision: 0.89,
      recall: 0.85,
      f1_score: 0.87,
      accuracy: 0.91,
      loss_history: [0.8, 0.6, 0.45, 0.35, 0.28, 0.25, 0.234],
      val_loss_history: [0.85, 0.65, 0.5, 0.4, 0.32, 0.3, 0.289],
    },
    config: {
      batch_size: 16,
      learning_rate: 0.00005,
      epochs: 10,
      warmup_steps: 500,
      weight_decay: 0.01,
      gradient_accumulation: 4,
      mixed_precision: true,
      bundeslaender: ['ni', 'by', 'nw', 'he', 'bw'],
    },
  },
]

export const MOCK_STATS: DatasetStats = {
  total_documents: 632,
  total_chunks: 8547,
  training_allowed: 489,
  by_bundesland: {
    ni: 87, by: 92, nw: 78, he: 65, bw: 71, rp: 43, sn: 38, sh: 34, th: 29,
  },
  by_doc_type: {
    verordnung: 312,
    schulordnung: 156,
    handreichung: 98,
    erlass: 66,
  },
}

// ============================================================================
// API FUNCTIONS
// ============================================================================

export async function fetchJobs(): Promise<TrainingJob[]> {
  try {
    const response = await fetch('/api/admin/training?action=jobs')
    if (!response.ok) throw new Error('Failed to fetch jobs')
    return await response.json()
  } catch (error) {
    console.error('Error fetching jobs:', error)
    return MOCK_JOBS
  }
}

export async function fetchDatasetStats(): Promise<DatasetStats> {
  try {
    const response = await fetch('/api/admin/training?action=dataset-stats')
    if (!response.ok) throw new Error('Failed to fetch stats')
    return await response.json()
  } catch (error) {
    console.error('Error fetching stats:', error)
    return MOCK_STATS
  }
}

export async function createTrainingJob(config: Partial<TrainingConfig>): Promise<{id: string, status: string}> {
  const response = await fetch('/api/admin/training?action=create-job', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      name: `Zeugnis-RAG ${new Date().toLocaleDateString('de-DE')}`,
      model_type: 'zeugnis',
      bundeslaender: config.bundeslaender || [],
      batch_size: config.batch_size || 16,
      learning_rate: config.learning_rate || 0.00005,
      epochs: config.epochs || 10,
      warmup_steps: config.warmup_steps || 500,
      weight_decay: config.weight_decay || 0.01,
      gradient_accumulation: config.gradient_accumulation || 4,
      mixed_precision: config.mixed_precision ?? true,
    }),
  })
  if (!response.ok) {
    const error = await response.json()
    throw new Error(error.detail || 'Failed to create job')
  }
  return await response.json()
}

export async function pauseJob(jobId: string): Promise<void> {
  const response = await fetch(`/api/admin/training?action=pause&job_id=${jobId}`, { method: 'POST' })
  if (!response.ok) throw new Error('Failed to pause job')
}

export async function resumeJob(jobId: string): Promise<void> {
  const response = await fetch(`/api/admin/training?action=resume&job_id=${jobId}`, { method: 'POST' })
  if (!response.ok) throw new Error('Failed to resume job')
}

export async function cancelJob(jobId: string): Promise<void> {
  const response = await fetch(`/api/admin/training?action=cancel&job_id=${jobId}`, { method: 'POST' })
  if (!response.ok) throw new Error('Failed to cancel job')
}
