/**
 * API V2 Type Definitions
 * External Authentication & Task Management
 */

// ==================== Authentication ====================

export interface UserInfo {
  id: number
  email: string
  display_name: string | null
}

export interface LoginResponseV2 {
  access_token: string
  token_type: string
  expires_in: number
  user: UserInfo
}

export interface UserResponse {
  id: number
  email: string
  display_name: string | null
  created_at: string
  last_login: string | null
  is_active: boolean
}

export interface SessionInfo {
  id: number
  token_type: string
  expires_at: string
  issued_at: string
  ip_address: string | null
  user_agent: string | null
  created_at: string
  last_accessed_at: string
  is_expired: boolean
  time_until_expiry: number
}

// ==================== Task Management ====================

export type TaskStatus = 'pending' | 'processing' | 'completed' | 'failed'

// ==================== Dual-Track Processing ====================

export type ProcessingTrack = 'ocr' | 'direct' | 'hybrid' | 'auto'

export interface ProcessingMetadata {
  processing_track: ProcessingTrack
  processing_time_seconds: number
  language: string
  page_count: number
  total_elements: number
  total_text_regions: number
  total_tables: number
  total_images: number
  average_confidence: number | null
  unified_format: boolean
}

export interface DocumentAnalysisResponse {
  task_id: string
  filename: string
  recommended_track: ProcessingTrack
  confidence: number
  reason: string
  document_info: Record<string, any>
  is_editable: boolean
  text_coverage: number | null
  page_count: number | null
}

/**
 * Layout detection model selection for OCR track.
 * Different models are optimized for different document types:
 * - chinese: PP-DocLayout_plus-L - Best for Chinese forms, contracts, invoices
 * - default: PubLayNet-based - Best for English academic papers
 * - cdla: Specialized for Chinese document layout analysis
 */
export type LayoutModel = 'chinese' | 'default' | 'cdla'

/**
 * Preprocessing mode for layout detection enhancement.
 * - auto: Analyze image quality and automatically apply optimal preprocessing
 * - manual: Use user-specified preprocessing configuration
 * - disabled: Skip preprocessing entirely
 */
export type PreprocessingMode = 'auto' | 'manual' | 'disabled'

/**
 * Contrast enhancement method for preprocessing.
 * - none: No contrast enhancement
 * - histogram: Standard histogram equalization
 * - clahe: Contrast Limited Adaptive Histogram Equalization (good for most cases)
 * - document: Background normalization + CLAHE (best for scanned documents)
 */
export type PreprocessingContrast = 'none' | 'histogram' | 'clahe' | 'document'

/**
 * Preprocessing configuration for layout detection enhancement.
 */
export interface PreprocessingConfig {
  contrast: PreprocessingContrast
  contrast_strength: number  // 0.5-3.0, default 1.0
  sharpen: boolean
  sharpen_strength: number   // 0.5-2.0, default 1.0
  binarize: boolean
  remove_scan_artifacts: boolean  // Remove horizontal scan line artifacts
}

/**
 * Image quality metrics from auto-analysis.
 */
export interface ImageQualityMetrics {
  contrast: number
  edge_strength: number
}

/**
 * Request for preprocessing preview.
 */
export interface PreprocessingPreviewRequest {
  page?: number
  mode?: PreprocessingMode
  config?: PreprocessingConfig
}

/**
 * Response for preprocessing preview.
 */
export interface PreprocessingPreviewResponse {
  original_url: string
  preprocessed_url: string
  quality_metrics: ImageQualityMetrics
  auto_config: PreprocessingConfig
  mode_used: PreprocessingMode
}

export interface ProcessingOptions {
  use_dual_track?: boolean
  force_track?: ProcessingTrack
  language?: string
  include_layout?: boolean
  include_images?: boolean
  layout_model?: LayoutModel  // Layout detection model selection (OCR track only)
  preprocessing_mode?: PreprocessingMode  // Preprocessing mode (OCR track only)
  preprocessing_config?: PreprocessingConfig  // Manual preprocessing config
}

export interface TaskCreate {
  filename?: string
  file_type?: string
}

export interface TaskUpdate {
  status?: TaskStatus
  error_message?: string
  processing_time_ms?: number
  result_json_path?: string
  result_markdown_path?: string
  result_pdf_path?: string
}

export interface Task {
  id: number
  user_id: number
  task_id: string
  filename: string | null
  file_type: string | null
  status: TaskStatus
  result_json_path: string | null
  result_markdown_path: string | null
  result_pdf_path: string | null
  error_message: string | null
  processing_time_ms: number | null
  created_at: string
  updated_at: string
  completed_at: string | null
  file_deleted: boolean
  // Dual-track processing fields
  processing_track?: ProcessingTrack
  processing_metadata?: ProcessingMetadata
}

export interface TaskFile {
  id: number
  original_name: string | null
  stored_path: string | null
  file_size: number | null
  mime_type: string | null
  file_hash: string | null
  created_at: string
}

export interface TaskDetail extends Task {
  files: TaskFile[]
}

export interface TaskListResponse {
  tasks: Task[]
  total: number
  page: number
  page_size: number
  has_more: boolean
}

export interface TaskStats {
  total: number
  pending: number
  processing: number
  completed: number
  failed: number
}

// ==================== Task Filters ====================

export interface TaskFilters {
  status?: TaskStatus
  page: number
  page_size: number
  order_by: string
  order_desc: boolean
}

// ==================== Admin Types ====================

export interface SystemStats {
  total_users: number
  active_users: number
  total_tasks: number
  total_sessions: number
  recent_activity_count: number
  task_stats: {
    pending: number
    processing: number
    completed: number
    failed: number
  }
}

export interface UserWithStats {
  id: number
  email: string
  display_name: string | null
  created_at: string
  last_login: string | null
  is_active: boolean
  task_count: number
  completed_tasks: number
  failed_tasks: number
}

export interface TopUser {
  user_id: number
  email: string
  display_name: string | null
  task_count: number
  completed_tasks: number
}

export interface AuditLog {
  id: number
  user_id: number
  user_email: string
  category: 'auth' | 'task' | 'file' | 'admin' | 'system'
  action: string
  resource_type: string | null
  resource_id: string | null
  success: boolean
  error_message: string | null
  extra_data: string | null
  created_at: string
}

export interface AuditLogListResponse {
  logs: AuditLog[]
  total: number
  page: number
  page_size: number
  has_more: boolean
}

export interface UserActivitySummary {
  user_id: number
  email: string
  display_name: string | null
  total_actions: number
  successful_actions: number
  failed_actions: number
  categories: Record<string, number>
  recent_actions: AuditLog[]
}

// ==================== Translation Types ====================

export type TranslationStatus = 'pending' | 'loading_model' | 'translating' | 'completed' | 'failed'

export interface TranslationRequest {
  target_lang: string
  source_lang?: string
}

export interface TranslationProgress {
  current_page: number
  total_pages: number
  current_element: number
  total_elements: number
  percentage: number
}

export interface TranslationStartResponse {
  task_id: string
  status: TranslationStatus
  target_lang: string
  message: string
}

export interface TranslationStatusResponse {
  task_id: string
  status: TranslationStatus
  target_lang: string
  progress: TranslationProgress | null
  error_message: string | null
  started_at: string | null
  completed_at: string | null
}

export interface TranslationStatistics {
  total_elements: number
  translated_elements: number
  skipped_elements: number
  total_characters: number
  processing_time_seconds: number
}

export interface TranslationListItem {
  target_lang: string
  translated_at: string
  model: string
  statistics: TranslationStatistics
  file_path: string
}

export interface TranslationListResponse {
  task_id: string
  translations: TranslationListItem[]
}

export interface TranslationResult {
  schema_version: string
  source_document: string
  source_lang: string
  target_lang: string
  model: string
  model_version: string
  translated_at: string
  statistics: TranslationStatistics
  translations: Record<string, any>
}

// ==================== Shared Types (from api.ts) ====================

/**
 * Authentication request for login
 */
export interface LoginRequest {
  username: string
  password: string
}

/**
 * Legacy login response (V1 API)
 * @deprecated Use LoginResponseV2 for V2 API
 */
export interface LoginResponse {
  access_token: string
  token_type: string
  expires_in: number
}

/**
 * User information (used by authStore)
 */
export interface User {
  id: number
  username: string
  email?: string
  displayName?: string | null
}

/**
 * File information for upload tracking
 */
export interface FileInfo {
  id: number
  filename: string
  file_size: number
  file_format: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
}

/**
 * File result for batch processing display
 */
export interface FileResult {
  id: number
  filename: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  processing_time?: number
  error?: string
}

/**
 * Export configuration rule
 */
export interface ExportRule {
  id: number
  rule_name: string
  config_json: Record<string, any>
  css_template?: string
  created_at: string
}

/**
 * Export request options
 */
export interface ExportRequest {
  batch_id: number
  format: 'txt' | 'json' | 'excel' | 'markdown' | 'pdf'
  rule_id?: number
  options?: ExportOptions
}

/**
 * Export additional options
 */
export interface ExportOptions {
  confidence_threshold?: number
  include_metadata?: boolean
  filename_pattern?: string
  css_template?: string
}

/**
 * CSS template for export styling
 */
export interface CSSTemplate {
  name: string
  description: string
}

/**
 * API error response
 */
export interface ApiError {
  detail: string
  status_code: number
}
