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

// ============================================================================
// MOCK DATA
// ============================================================================

export const MOCK_JOBS: TrainingJob[] = []

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,
  },
}

export const MOCK_DATA_SOURCES: DataSource[] = [
  {
    id: 'nibis',
    name: 'NiBiS Erwartungshorizonte',
    description: 'Offizielle Abitur-Erwartungshorizonte vom Niedersaechsischen Bildungsserver',
    collection: 'bp_nibis_eh',
    document_count: 245,
    chunk_count: 3200,
    last_updated: '2025-01-15T10:30:00Z',
    status: 'active',
  },
  {
    id: 'user_eh',
    name: 'Benutzerdefinierte EH',
    description: 'Von Lehrern hochgeladene schulspezifische Erwartungshorizonte',
    collection: 'bp_eh',
    document_count: 87,
    chunk_count: 1100,
    last_updated: '2025-01-20T14:15:00Z',
    status: 'active',
  },
  {
    id: 'legal',
    name: 'Rechtskorpus',
    description: 'DSGVO, AI Act, BSI-Standards und weitere Compliance-Regelwerke',
    collection: 'bp_legal_corpus',
    document_count: 19,
    chunk_count: 2400,
    last_updated: '2025-01-10T08:00:00Z',
    status: 'active',
  },
  {
    id: 'dsfa',
    name: 'DSFA-Guidance',
    description: 'WP248, DSK Kurzpapiere, Muss-Listen aller Bundeslaender mit Quellenattribution',
    collection: 'bp_dsfa_corpus',
    document_count: 45,
    chunk_count: 850,
    last_updated: '2026-02-09T10:00:00Z',
    status: 'active',
  },
  {
    id: 'schulordnungen',
    name: 'Schulordnungen',
    description: 'Landesschulordnungen und Zeugnisverordnungen aller Bundeslaender',
    collection: 'bp_schulordnungen',
    document_count: 156,
    chunk_count: 1847,
    last_updated: null,
    status: 'pending',
  },
]

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

export async function fetchJobs(): Promise<TrainingJob[]> {
  try {
    const response = await fetch('/api/ai/rag-pipeline?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/ai/rag-pipeline?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/ai/rag-pipeline?action=create-job', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      name: `RAG-Index ${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/ai/rag-pipeline?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/ai/rag-pipeline?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/ai/rag-pipeline?action=cancel&job_id=${jobId}`, {
    method: 'POST',
  })
  if (!response.ok) throw new Error('Failed to cancel job')
}
