/**
 * 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
  severity: SeverityLevel
  category: string
  isActive: boolean
}

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
  triggerCondition: string
  severity: SeverityLevel
  category: string
}

export interface UpdateRuleRequest {
  name?: string
  description?: string
  triggerCondition?: string
  severity?: SeverityLevel
  category?: string
  isActive?: 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/configuration`)
  },

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

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

  applyPreset: async (projectId: string, preset: ReviewPreset): Promise<ReviewConfiguration> => {
    return await api.post(`/projects/${projectId}/review/configuration/preset`, { preset })
  },

  // Custom Rules
  getRules: async (projectId: string): Promise<ReviewRule[]> => {
    return await api.get(`/projects/${projectId}/review/rules`)
  },

  createRule: async (projectId: string, data: CreateRuleRequest): Promise<ReviewRule> => {
    return await api.post(`/projects/${projectId}/review/rules`, data)
  },

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

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

  testRule: async (projectId: string, data: TestRuleRequest): Promise<TestRuleResponse> => {
    return await api.post(`/projects/${projectId}/review/rules/test`, data)
  },

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

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

  getReviewResult: async (projectId: string, reviewId: string): Promise<ReviewResult> => {
    return await api.get(`/projects/${projectId}/review/results/${reviewId}`)
  },

  getLatestReviewResult: async (projectId: string, episodeNumber?: number): Promise<ReviewResult> => {
    return await api.get(`/projects/${projectId}/review/latest`, { params: { episode_number: episodeNumber } })
  },

  // Issue Management
  ignoreIssue: async (projectId: string, issueId: string): Promise<void> => {
    return await api.post(`/projects/${projectId}/review/issues/${issueId}/ignore`)
  },

  unignoreIssue: async (projectId: string, issueId: string): Promise<void> => {
    return await api.post(`/projects/${projectId}/review/issues/${issueId}/unignore`)
  },

  autoFixIssue: async (projectId: string, issueId: string): Promise<{ fixed: boolean; fixedText?: string }> => {
    return await api.post(`/projects/${projectId}/review/issues/${issueId}/autofix`)
  },

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

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