/**
 * Klausur Service API - Core types and Klausur/Student API
 *
 * Split into:
 * - api.ts (this file): Core types, auth, base API, klausurApi, uploadStudentWork
 * - api-eh-types.ts: BYOEH type definitions
 * - api-eh.ts: ehApi and klausurEHApi
 */

// Re-export EH types and API for backward compatibility
export type {
  Erwartungshorizont, EHRAGResult, EHAuditEntry, EHKeyShare, EHKlausurLink,
  SharedEHInfo, LinkedEHInfo, EHShareInvitation, PendingInvitationInfo,
  SentInvitationInfo, EHAccessChain,
} from './api-eh-types'

export { ehApi, klausurEHApi } from './api-eh'

// ============================================================================
// Core Types
// ============================================================================

export interface StudentKlausur {
  id: string; klausur_id: string; student_name: string; student_id: string | null;
  file_path: string | null; ocr_text: string | null; status: string;
  criteria_scores: Record<string, { score: number; annotations: string[] }>;
  gutachten: { einleitung: string; hauptteil: string; fazit: string; staerken: string[]; schwaechen: string[] } | null;
  raw_points: number; grade_points: number; created_at: string
}

export interface Klausur {
  id: string; title: string; subject: string; modus: 'landes_abitur' | 'vorabitur';
  class_id: string | null; year: number; semester: string;
  erwartungshorizont: Record<string, unknown> | null; student_count: number;
  students: StudentKlausur[]; created_at: string; teacher_id: string
}

export interface GradeInfo {
  thresholds: Record<number, number>; labels: Record<number, string>;
  criteria: Record<string, { weight: number; label: string }>
}

// ============================================================================
// Auth & Base API
// ============================================================================

export function getAuthToken(): string | null {
  try {
    if (window.parent !== window) {
      const parentToken = (window.parent as unknown as { authToken?: string }).authToken
      if (parentToken) return parentToken
    }
  } catch { /* Cross-origin */ }
  return localStorage.getItem('auth_token')
}

export async function apiCall<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
  const token = getAuthToken()
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(options.headers as Record<string, string> || {})
  }
  if (token) headers['Authorization'] = `Bearer ${token}`
  const response = await fetch(`/api/v1${endpoint}`, { ...options, headers })
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Request failed' }))
    throw new Error(error.detail || `HTTP ${response.status}`)
  }
  return response.json()
}

// ============================================================================
// Klausuren API
// ============================================================================

export const klausurApi = {
  listKlausuren: (): Promise<Klausur[]> => apiCall('/klausuren'),
  getKlausur: (id: string): Promise<Klausur> => apiCall(`/klausuren/${id}`),
  createKlausur: (data: Partial<Klausur>): Promise<Klausur> => apiCall('/klausuren', { method: 'POST', body: JSON.stringify(data) }),
  updateKlausur: (id: string, data: Partial<Klausur>): Promise<Klausur> => apiCall(`/klausuren/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  deleteKlausur: (id: string): Promise<{ success: boolean }> => apiCall(`/klausuren/${id}`, { method: 'DELETE' }),

  listStudents: (klausurId: string): Promise<StudentKlausur[]> => apiCall(`/klausuren/${klausurId}/students`),
  deleteStudent: (studentId: string): Promise<{ success: boolean }> => apiCall(`/students/${studentId}`, { method: 'DELETE' }),

  updateCriteria: (studentId: string, criterion: string, score: number, annotations?: string[]): Promise<StudentKlausur> =>
    apiCall(`/students/${studentId}/criteria`, { method: 'PUT', body: JSON.stringify({ criterion, score, annotations }) }),

  updateGutachten: (studentId: string, gutachten: { einleitung: string; hauptteil: string; fazit: string; staerken?: string[]; schwaechen?: string[] }): Promise<StudentKlausur> =>
    apiCall(`/students/${studentId}/gutachten`, { method: 'PUT', body: JSON.stringify(gutachten) }),

  finalizeStudent: (studentId: string): Promise<StudentKlausur> => apiCall(`/students/${studentId}/finalize`, { method: 'POST' }),

  generateGutachten: (studentId: string, options: { include_strengths?: boolean; include_weaknesses?: boolean; tone?: 'formal' | 'friendly' | 'constructive' } = {}): Promise<{ einleitung: string; hauptteil: string; fazit: string; staerken: string[]; schwaechen: string[]; generated_at: string; is_ki_generated: boolean; tone: string }> =>
    apiCall(`/students/${studentId}/gutachten/generate`, { method: 'POST', body: JSON.stringify({ include_strengths: options.include_strengths ?? true, include_weaknesses: options.include_weaknesses ?? true, tone: options.tone ?? 'formal' }) }),

  getFairnessAnalysis: (klausurId: string): Promise<{ klausur_id: string; students_count: number; graded_count: number; statistics: { average_grade: number; average_raw_points: number; min_grade: number; max_grade: number; spread: number; standard_deviation: number }; criteria_breakdown: Record<string, { average: number; min: number; max: number; count: number }>; outliers: Array<{ student_id: string; student_name: string; grade_points: number; deviation: number; direction: 'above' | 'below' }>; fairness_score: number; warnings: string[]; recommendation: string }> =>
    apiCall(`/klausuren/${klausurId}/fairness`),

  getStudentAuditLog: (studentId: string): Promise<Array<{ id: string; timestamp: string; user_id: string; action: string; entity_type: string; entity_id: string; field: string | null; old_value: string | null; new_value: string | null; details: Record<string, unknown> | null }>> =>
    apiCall(`/students/${studentId}/audit-log`),

  getGradeInfo: (): Promise<GradeInfo> => apiCall('/grade-info'),
}

// ============================================================================
// File Upload
// ============================================================================

export async function uploadStudentWork(klausurId: string, studentName: string, file: File): Promise<StudentKlausur> {
  const token = getAuthToken()
  const formData = new FormData()
  formData.append('file', file)
  formData.append('student_name', studentName)
  const headers: Record<string, string> = {}
  if (token) headers['Authorization'] = `Bearer ${token}`
  const response = await fetch(`/api/v1/klausuren/${klausurId}/students`, { method: 'POST', headers, body: formData })
  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: 'Upload failed' }))
    throw new Error(error.detail || `HTTP ${response.status}`)
  }
  return response.json()
}
