export type PipelineStepStatus = 'pending' | 'active' | 'completed' | 'failed' | 'skipped'

export interface PipelineStep {
  id: string
  name: string
  icon: string
  status: PipelineStepStatus
}

export type DocumentCategory =
  | 'vokabelseite' | 'buchseite' | 'arbeitsblatt' | 'klausurseite'
  | 'mathearbeit' | 'statistik' | 'zeitung' | 'formular' | 'handschrift' | 'sonstiges'

export const DOCUMENT_CATEGORIES: { value: DocumentCategory; label: string; icon: string }[] = [
  { value: 'vokabelseite', label: 'Vokabelseite', icon: '📖' },
  { value: 'buchseite', label: 'Buchseite', icon: '📚' },
  { value: 'arbeitsblatt', label: 'Arbeitsblatt', icon: '📝' },
  { value: 'klausurseite', label: 'Klausurseite', icon: '📄' },
  { value: 'mathearbeit', label: 'Mathearbeit', icon: '🔢' },
  { value: 'statistik', label: 'Statistik', icon: '📊' },
  { value: 'zeitung', label: 'Zeitung', icon: '📰' },
  { value: 'formular', label: 'Formular', icon: '📋' },
  { value: 'handschrift', label: 'Handschrift', icon: '✍️' },
  { value: 'sonstiges', label: 'Sonstiges', icon: '📎' },
]

export interface SessionListItem {
  id: string
  name: string
  filename: string
  status: string
  current_step: number
  document_category?: DocumentCategory
  doc_type?: string
  created_at: string
  updated_at?: string
  parent_session_id?: string | null
  box_index?: number | null
}

export interface SubSession {
  id: string
  name: string
  box_index: number
  current_step?: number
  status?: string
}

export interface PipelineLogEntry {
  step: string
  completed_at: string
  success: boolean
  duration_ms?: number
  metrics: Record<string, unknown>
}

export interface PipelineLog {
  steps: PipelineLogEntry[]
}

export interface DocumentTypeResult {
  doc_type: 'vocab_table' | 'full_text' | 'generic_table'
  confidence: number
  pipeline: 'cell_first' | 'full_page'
  skip_steps: string[]
  features?: Record<string, unknown>
  duration_seconds?: number
}

export interface OrientationResult {
  orientation_degrees: number
  corrected: boolean
  duration_seconds: number
}

export interface CropResult {
  crop_applied: boolean
  crop_rect?: { x: number; y: number; width: number; height: number }
  crop_rect_pct?: { x: number; y: number; width: number; height: number }
  original_size: { width: number; height: number }
  cropped_size: { width: number; height: number }
  detected_format?: string
  format_confidence?: number
  aspect_ratio?: number
  border_fractions?: { top: number; bottom: number; left: number; right: number }
  skipped?: boolean
  duration_seconds?: number
}

export interface SessionInfo {
  session_id: string
  filename: string
  name?: string
  image_width: number
  image_height: number
  original_image_url: string
  current_step?: number
  document_category?: DocumentCategory
  doc_type?: string
  orientation_result?: OrientationResult
  crop_result?: CropResult
  deskew_result?: DeskewResult
  dewarp_result?: DewarpResult
  column_result?: ColumnResult
  row_result?: RowResult
  word_result?: GridResult
  doc_type_result?: DocumentTypeResult
  sub_sessions?: SubSession[]
  parent_session_id?: string
  box_index?: number
}

export interface DeskewResult {
  session_id: string
  angle_hough: number
  angle_word_alignment: number
  angle_iterative?: number
  angle_residual?: number
  angle_textline?: number
  angle_applied: number
  method_used: 'hough' | 'word_alignment' | 'manual' | 'iterative' | 'two_pass' | 'three_pass' | 'manual_combined'
  confidence: number
  duration_seconds: number
  deskewed_image_url: string
  binarized_image_url: string
}

export interface DeskewGroundTruth {
  is_correct: boolean
  corrected_angle?: number
  notes?: string
}

export interface DewarpDetection {
  method: string
  shear_degrees: number
  confidence: number
}

export interface DewarpResult {
  session_id: string
  method_used: string
  shear_degrees: number
  confidence: number
  duration_seconds: number
  dewarped_image_url: string
  detections?: DewarpDetection[]
}

export interface DewarpGroundTruth {
  is_correct: boolean
  corrected_shear?: number
  notes?: string
}

export interface PageRegion {
  type: 'column_en' | 'column_de' | 'column_example' | 'page_ref'
      | 'column_marker' | 'column_text' | 'column_ignore' | 'header' | 'footer'
  x: number
  y: number
  width: number
  height: number
  classification_confidence?: number
  classification_method?: string
}

export interface PageZone {
  zone_type: 'content' | 'box'
  y_start: number
  y_end: number
  box?: { x: number; y: number; width: number; height: number }
}

export interface ColumnResult {
  columns: PageRegion[]
  duration_seconds: number
  zones?: PageZone[]
}

export interface ColumnGroundTruth {
  is_correct: boolean
  corrected_columns?: PageRegion[]
  notes?: string
}

export interface ManualColumnDivider {
  xPercent: number  // Position in % of image width (0-100)
}

export type ColumnTypeKey = PageRegion['type']

export interface RowResult {
  rows: RowItem[]
  summary: Record<string, number>
  total_rows: number
  duration_seconds: number
}

export interface RowItem {
  index: number
  x: number
  y: number
  width: number
  height: number
  word_count: number
  row_type: 'content' | 'header' | 'footer'
  gap_before: number
}

export interface RowGroundTruth {
  is_correct: boolean
  corrected_rows?: RowItem[]
  notes?: string
}

export interface StructureGraphic {
  x: number
  y: number
  w: number
  h: number
  area: number
  shape: string   // image, illustration
  color_name: string
  color_hex: string
  confidence: number
}

export interface ExcludeRegion {
  x: number
  y: number
  w: number
  h: number
  label?: string
}

export interface DocLayoutRegion {
  x: number
  y: number
  w: number
  h: number
  class_name: string
  confidence: number
}

export interface StructureResult {
  image_width: number
  image_height: number
  content_bounds: { x: number; y: number; w: number; h: number }
  boxes: StructureBox[]
  zones: StructureZone[]
  graphics: StructureGraphic[]
  exclude_regions?: ExcludeRegion[]
  color_pixel_counts: Record<string, number>
  has_words: boolean
  word_count: number
  border_ghosts_removed?: number
  duration_seconds: number
  /** PP-DocLayout regions (only present when method=ppdoclayout) */
  layout_regions?: DocLayoutRegion[]
  detection_method?: 'opencv' | 'ppdoclayout'
}

export interface StructureBox {
  x: number
  y: number
  w: number
  h: number
  confidence: number
  border_thickness: number
  bg_color_name?: string
  bg_color_hex?: string
}

export interface StructureZone {
  index: number
  zone_type: 'content' | 'box'
  x: number
  y: number
  w: number
  h: number
}

export interface WordBbox {
  x: number
  y: number
  w: number
  h: number
}

export interface OcrWordBox {
  text: string
  left: number    // absolute image x in px
  top: number     // absolute image y in px
  width: number   // px
  height: number  // px
  conf: number
  color?: string       // hex color of detected text, e.g. '#dc2626'
  color_name?: string  // 'black' | 'red' | 'blue' | 'green' | 'orange' | 'purple' | 'yellow'
  recovered?: boolean  // true if this word was recovered via color detection
}

export interface GridCell {
  cell_id: string          // "R03_C1"
  row_index: number
  col_index: number
  col_type: string
  text: string
  confidence: number
  bbox_px: WordBbox
  bbox_pct: WordBbox
  ocr_engine?: string
  is_bold?: boolean
  status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
  word_boxes?: OcrWordBox[]  // per-word bounding boxes from OCR engine
}

export interface ColumnMeta {
  index: number
  type: string
  x: number
  width: number
}

export interface GridResult {
  cells: GridCell[]
  grid_shape: { rows: number; cols: number; total_cells: number }
  columns_used: ColumnMeta[]
  layout: 'vocab' | 'generic'
  image_width: number
  image_height: number
  duration_seconds: number
  ocr_engine?: string
  vocab_entries?: WordEntry[]   // Only when layout='vocab'
  entries?: WordEntry[]         // Backwards compat alias for vocab_entries
  entry_count?: number
  summary: {
    total_cells: number
    non_empty_cells: number
    low_confidence: number
    // Only when layout='vocab':
    total_entries?: number
    with_english?: number
    with_german?: number
  }
  llm_review?: {
    changes: { row_index: number; field: string; old: string; new: string }[]
    model_used: string
    duration_ms: number
    entries_corrected: number
    applied_count?: number
    applied_at?: string
  }
}

export interface WordEntry {
  row_index: number
  english: string
  german: string
  example: string
  source_page?: string
  marker?: string
  confidence: number
  bbox: WordBbox
  bbox_en: WordBbox | null
  bbox_de: WordBbox | null
  bbox_ex: WordBbox | null
  bbox_ref?: WordBbox | null
  bbox_marker?: WordBbox | null
  status?: 'pending' | 'confirmed' | 'edited' | 'skipped'
}

/** @deprecated Use GridResult instead */
export interface WordResult {
  entries: WordEntry[]
  entry_count: number
  image_width: number
  image_height: number
  duration_seconds: number
  ocr_engine?: string
  summary: {
    total_entries: number
    with_english: number
    with_german: number
    low_confidence: number
  }
}

export interface WordGroundTruth {
  is_correct: boolean
  corrected_entries?: WordEntry[]
  notes?: string
}

export interface ImageRegion {
  bbox_pct: { x: number; y: number; w: number; h: number }
  prompt: string
  description: string
  image_b64: string | null
  style: 'educational' | 'cartoon' | 'sketch' | 'clipart' | 'realistic'
}

export type ImageStyle = ImageRegion['style']

export const IMAGE_STYLES: { value: ImageStyle; label: string }[] = [
  { value: 'educational', label: 'Lehrbuch' },
  { value: 'cartoon', label: 'Cartoon' },
  { value: 'sketch', label: 'Skizze' },
  { value: 'clipart', label: 'Clipart' },
  { value: 'realistic', label: 'Realistisch' },
]

export const PIPELINE_STEPS: PipelineStep[] = [
  { id: 'orientation', name: 'Orientierung', icon: '🔄', status: 'pending' },
  { id: 'deskew', name: 'Begradigung', icon: '📐', status: 'pending' },
  { id: 'dewarp', name: 'Entzerrung', icon: '🔧', status: 'pending' },
  { id: 'crop', name: 'Zuschneiden', icon: '✂️', status: 'pending' },
  { id: 'columns', name: 'Spalten', icon: '📊', status: 'pending' },
  { id: 'rows', name: 'Zeilen', icon: '📏', status: 'pending' },
  { id: 'words', name: 'Woerter', icon: '🔤', status: 'pending' },
  { id: 'structure', name: 'Struktur', icon: '🔍', status: 'pending' },
  { id: 'llm-review', name: 'Korrektur', icon: '✏️', status: 'pending' },
  { id: 'reconstruction', name: 'Rekonstruktion', icon: '🏗️', status: 'pending' },
  { id: 'ground-truth', name: 'Validierung', icon: '✅', status: 'pending' },
]
