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

// Types
export type ImportanceLevel = 'high' | 'medium' | 'low'
export type ThreadStatus = 'pending' | 'in_progress' | 'resolved'
export type RelationType = 'friend' | 'enemy' | 'family' | 'romantic' | 'mentor' | 'rival' | 'ally' | 'neutral'

export interface TimelineEvent {
  id: string
  episodeNumber: number
  timestamp: string
  characters: string[]
  description: string
  importance: ImportanceLevel
  category: string
  createdAt: string
}

export interface PendingThread {
  id: string
  description: string
  importance: ImportanceLevel
  status: ThreadStatus
  reminderEpisode?: number
  relatedCharacters?: string[]
  createdAt: string
  resolvedAt?: string
}

export interface CharacterState {
  characterName: string
  currentState: string
  history: StateHistoryEntry[]
}

export interface StateHistoryEntry {
  episodeNumber: number
  state: string
  timestamp: string
}

export interface Foreshadowing {
  id: string
  description: string
  importance: ImportanceLevel
  payoffEventId?: string
  payoffEpisode?: number
  status: 'planted' | 'partially_paid' | 'paid_off'
  plantedEpisode: number
  createdAt: string
}

export interface Relationship {
  sourceCharacter: string
  targetCharacter: string
  relationType: RelationType
  strength: number // 0-100
  description?: string
  evolutionHistory: RelationshipEvolution[]
}

export interface RelationshipEvolution {
  episodeNumber: number
  relationType: RelationType
  strength: number
  description?: string
}

export interface MemoryStatistics {
  totalEvents: number
  totalThreads: number
  resolvedThreads: number
  totalCharacters: number
  totalForeshadowing: number
  paidOffForeshadowing: number
  totalRelationships: number
}

export interface MemorySystem {
  projectId: string
  timeline: TimelineEvent[]
  pendingThreads: PendingThread[]
  characterStates: CharacterState[]
  foreshadowing: Foreshadowing[]
  relationships: Relationship[]
  statistics: MemoryStatistics
}

// Requests
export interface CreateThreadRequest {
  description: string
  importance: ImportanceLevel
  reminderEpisode?: number
  relatedCharacters?: string[]
}

export interface UpdateThreadRequest {
  description?: string
  importance?: ImportanceLevel
  status?: ThreadStatus
  reminderEpisode?: number
  relatedCharacters?: string[]
}

export interface CreateForeshadowingRequest {
  description: string
  importance: ImportanceLevel
  plantedEpisode: number
}

export interface UpdateForeshadowingRequest {
  description?: string
  importance?: ImportanceLevel
  status?: 'planted' | 'partially_paid' | 'paid_off'
  payoffEventId?: string
  payoffEpisode?: number
}

export const memoryService = {
  // Get memory system
  getMemory: async (projectId: string): Promise<MemorySystem> => {
    return await api.get(`/projects/${projectId}/memory`)
  },

  // Timeline
  getTimeline: async (projectId: string, filters?: {
    character?: string
    episode?: number
    importance?: ImportanceLevel
  }): Promise<TimelineEvent[]> => {
    return await api.get(`/projects/${projectId}/memory/timeline`, { params: filters })
  },

  addTimelineEvent: async (projectId: string, event: Omit<TimelineEvent, 'id' | 'createdAt'>): Promise<TimelineEvent> => {
    return await api.post(`/projects/${projectId}/memory/timeline`, event)
  },

  // Pending Threads
  getThreads: async (projectId: string): Promise<PendingThread[]> => {
    return await api.get(`/projects/${projectId}/memory/threads`)
  },

  createThread: async (projectId: string, data: CreateThreadRequest): Promise<PendingThread> => {
    return await api.post(`/projects/${projectId}/memory/threads`, data)
  },

  updateThread: async (projectId: string, threadId: string, data: UpdateThreadRequest): Promise<PendingThread> => {
    return await api.put(`/projects/${projectId}/memory/threads/${threadId}`, data)
  },

  deleteThread: async (projectId: string, threadId: string): Promise<void> => {
    return await api.delete(`/projects/${projectId}/memory/threads/${threadId}`)
  },

  resolveThread: async (projectId: string, threadId: string): Promise<PendingThread> => {
    return await api.post(`/projects/${projectId}/memory/threads/${threadId}/resolve`)
  },

  // Character States
  getCharacterStates: async (projectId: string): Promise<CharacterState[]> => {
    return await api.get(`/projects/${projectId}/memory/characters`)
  },

  getCharacterState: async (projectId: string, characterName: string): Promise<CharacterState> => {
    return await api.get(`/projects/${projectId}/memory/characters/${encodeURIComponent(characterName)}`)
  },

  updateCharacterState: async (projectId: string, characterName: string, state: string): Promise<CharacterState> => {
    return await api.put(`/projects/${projectId}/memory/characters/${encodeURIComponent(characterName)}`, { state })
  },

  // Foreshadowing
  getForeshadowing: async (projectId: string): Promise<Foreshadowing[]> => {
    return await api.get(`/projects/${projectId}/memory/foreshadowing`)
  },

  createForeshadowing: async (projectId: string, data: CreateForeshadowingRequest): Promise<Foreshadowing> => {
    return await api.post(`/projects/${projectId}/memory/foreshadowing`, data)
  },

  updateForeshadowing: async (projectId: string, foreshadowingId: string, data: UpdateForeshadowingRequest): Promise<Foreshadowing> => {
    return await api.put(`/projects/${projectId}/memory/foreshadowing/${foreshadowingId}`, data)
  },

  deleteForeshadowing: async (projectId: string, foreshadowingId: string): Promise<void> => {
    return await api.delete(`/projects/${projectId}/memory/foreshadowing/${foreshadowingId}`)
  },

  // Relationships
  getRelationships: async (projectId: string): Promise<Relationship[]> => {
    return await api.get(`/projects/${projectId}/memory/relationships`)
  },

  updateRelationship: async (
    projectId: string,
    sourceCharacter: string,
    targetCharacter: string,
    data: {
      relationType: RelationType
      strength: number
      description?: string
    }
  ): Promise<Relationship> => {
    return await api.put(
      `/projects/${projectId}/memory/relationships/${encodeURIComponent(sourceCharacter)}/${encodeURIComponent(targetCharacter)}`,
      data
    )
  },

  // Statistics
  getStatistics: async (projectId: string): Promise<MemoryStatistics> => {
    return await api.get(`/projects/${projectId}/memory/statistics`)
  },
}
