/**
 * Review System API Service
 */
import api from './api'

// Types
export type SeverityLevel = 'low' | 'medium' | 'high'
export type ReviewPreset = 'draft' | 'standard' | 'strict' | 'custom'

export interface DimensionConfig {
  name: string
  enabled: boolean
  strictness: number // 0-100
  weight: number // 0-1
}

export interface ReviewRule {
  id: string
  name: string
  description: string
  triggerCondition: string  // Frontend format
  trigger_condition?: string  // Backend format
  severity: SeverityLevel
  category: string  // Frontend format
  dimension?: string  // Backend format
  isActive: boolean
  enabled?: boolean  // Backend format
}

export interface ReviewConfiguration {
  preset: ReviewPreset
  dimensions: {
    character_consistency: DimensionConfig
    plot_coherence: DimensionConfig
    dialogue_quality: DimensionConfig
    pacing: DimensionConfig
    emotional_depth: DimensionConfig
    thematic_strength: DimensionConfig
  }
  customRules: ReviewRule[]
  createdAt: string
  updatedAt: string
}

export interface Issue {
  id: string
  type: string
  dimension: string
  severity: SeverityLevel
  location: {
    episodeNumber?: number
    lineNumber?: number
    section?: string
  }
  originalText: string
  description: string
  suggestion?: string
  canAutoFix: boolean
  ignored: boolean
}

export interface DimensionScore {
  dimension: string
  score: number
  weight: number
  issues: Issue[]
}

export interface ReviewResult {
  projectId: string
  episodeNumber?: number
  overallScore: number
  dimensionScores: DimensionScore[]
  issues: Issue[]
  summary: string
  reviewedAt: string
  configuration: ReviewConfiguration
}

export interface TestRuleRequest {
  rule: ReviewRule
  sampleContent: string
}

export interface TestRuleResponse {
  triggered: boolean
  issues: Issue[]
  explanation: string
}

// Requests
export interface CreateConfigurationRequest {
  preset: ReviewPreset
  dimensions?: Partial<ReviewConfiguration['dimensions']>
  customRules?: Omit<ReviewRule, 'id'>[]
}

export interface CreateRuleRequest {
  name: string
  description: string
  trigger_condition: string
  severity: SeverityLevel
  dimension: string
}

export interface UpdateRuleRequest {
  name?: string
  description?: string
  trigger_condition?: string
  severity?: SeverityLevel
  dimension?: string
  enabled?: boolean
}

export interface ExecuteReviewRequest {
  episodeNumber?: number
  configuration?: ReviewConfiguration
}

export interface ExportReportRequest {
  format: 'json' | 'pdf' | 'markdown'
  includeIgnored?: boolean
}

export const reviewService = {
  // Configuration
  getConfiguration: async (projectId: string): Promise<ReviewConfiguration> => {
    return await api.get(`/projects/${projectId}/review-config`)
  },

  createConfiguration: async (projectId: string, data: CreateConfigurationRequest): Promise<ReviewConfiguration> => {
    return await api.post(`/projects/${projectId}/review-config`, data)
  },

  updateConfiguration: async (projectId: string, data: Partial<ReviewConfiguration>): Promise<ReviewConfiguration> => {
    return await api.put(`/projects/${projectId}/review-config`, data)
  },

  applyPreset: async (projectId: string, preset: ReviewPreset): Promise<ReviewConfiguration> => {
    // Apply preset by updating the configuration with the preset
    return await api.put(`/projects/${projectId}/review-config`, { preset })
  },

  // Custom Rules
  getRules: async (projectId: string): Promise<ReviewRule[]> => {
    return await api.get('/custom-rules', { params: { project_id: projectId } })
  },

  createRule: async (projectId: string, data: CreateRuleRequest): Promise<ReviewRule> => {
    return await api.post('/custom-rules', data, { params: { project_id: projectId } })
  },

  updateRule: async (projectId: string, ruleId: string, data: UpdateRuleRequest): Promise<ReviewRule> => {
    return await api.put(`/custom-rules/${ruleId}`, data, { params: { project_id: projectId } })
  },

  deleteRule: async (projectId: string, ruleId: string): Promise<void> => {
    return await api.delete(`/custom-rules/${ruleId}`, { params: { project_id: projectId } })
  },

  testRule: async (projectId: string, data: TestRuleRequest & { episodeId: string }): Promise<TestRuleResponse> => {
    return await api.post(`/custom-rules/${data.rule?.id || 'test'}/test`, {
      episode_id: data.episodeId,
      project_id: projectId
    })
  },

  // Rule Templates
  getRuleTemplates: async (): Promise<ReviewRule[]> => {
    return await api.get('/custom-rules')
  },

  // Review Execution
  executeReview: async (projectId: string, data: ExecuteReviewRequest): Promise<ReviewResult> => {
    return await api.post(`/projects/${projectId}/episodes/${data.episodeNumber || 1}/review`, data)
  },

  getReviewResult: async (projectId: string, episodeNumber: number): Promise<ReviewResult> => {
    return await api.get(`/projects/${projectId}/episodes/${episodeNumber}/review-result`)
  },

  getLatestReviewResult: async (projectId: string, episodeNumber?: number): Promise<ReviewResult> => {
    if (!episodeNumber) {
      throw new Error('episodeNumber is required')
    }
    return await api.get(`/projects/${projectId}/episodes/${episodeNumber}/review-result`)
  },

  // Issue Management
  ignoreIssue: async (projectId: string, issueId: string): Promise<void> => {
    return await api.post(`/custom-rules/${issueId}/ignore`, { project_id: projectId })
  },

  unignoreIssue: async (projectId: string, issueId: string): Promise<void> => {
    return await api.post(`/custom-rules/${issueId}/unignore`, { project_id: projectId })
  },

  autoFixIssue: async (projectId: string, issueId: string): Promise<{ fixed: boolean; fixedText?: string }> => {
    return await api.post(`/custom-rules/${issueId}/test`, { project_id: projectId })
  },

  applyBatchDecisions: async (
    projectId: string,
    decisions: { issueId: string; action: 'accept' | 'reject' | 'ignore' }[]
  ): Promise<{ applied: number }> => {
    return await api.post(`/projects/${projectId}/review-config`, { decisions })
  },

  // Export
  exportReport: async (projectId: string, reviewId: string, data: ExportReportRequest): Promise<Blob> => {
    const response = await api.get(`/projects/${projectId}/episodes/${reviewId}/review-result`, {
      params: data,
      responseType: 'blob'
    })
    return response
  },
}
