import axios from 'axios'
import { appNavigate, getRuntime, isAuthPath } from '../config/runtime'
import { clearAuth, getToken } from '../utils/auth'

function normalizeApiBase(base: string): string {
  const trimmed = base.trim().replace(/\/+$/, '')
  return trimmed || '/api'
}

let apiBaseURL = normalizeApiBase(getRuntime().apiBase)

const request = axios.create({
  baseURL: apiBaseURL,
  timeout: 15000,
})

export function setApiBaseURL(base: string) {
  apiBaseURL = normalizeApiBase(base)
  request.defaults.baseURL = apiBaseURL
}

if (typeof window !== 'undefined') {
  window.__wordloopSetApiBase = setApiBaseURL
}

request.interceptors.request.use((config) => {
  const token = getToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

request.interceptors.response.use(
  (res) => res,
  (err) => {
    if (err.response?.status === 401) {
      clearAuth()
      if (!isAuthPath()) {
        appNavigate('/login')
      }
    }
    return Promise.reject(err)
  }
)

export default request

export interface Word {
  id: number
  source_text: string
  target_text: string
  source_lang: string
  target_lang: string
  phonetic?: string
  example_en?: string
  example_cn?: string
  status: string
  correct_count: number
  wrong_count: number
  consecutive_correct_count: number
  mastery_score: number
  train_count?: number
  total_train_seconds?: number
  review_due_date?: string
  last_reviewed_at?: string
  created_at: string
  entered_at: string
}

export interface MemoryCurvePoint {
  day_index: number
  date: string
  forgetting: number
  mastery: number
  risk: number
}

export interface MemoryFutureRiskPoint {
  day_offset: number
  date: string
  risk: number
}

export interface MemoryGraphNode {
  id: string
  label: string
  zh: string
  status: string
  mastery: number
  entered_at: string
  size: number
}

export interface MemoryGraphLink {
  source: string
  target: string
  kind: string
  strength: number
}

export interface MemoryWordSummary {
  id: number
  en: string
  zh: string
  status: string
  mastery_score: number
  correct_count: number
  wrong_count: number
  train_count: number
  total_train_seconds: number
  entered_at: string
  retention_now: number
  risk_7d: number
}

export interface WordMemoryCurvePoint {
  date: string
  datetime: string
  forgetting: number
  mastery: number
  risk: number
  wrong_count: number
  train_count: number
  train_seconds: number
  is_correct?: boolean | null
}

export interface WordMemoryDetail {
  word_id: number
  en: string
  zh: string
  correct_count: number
  wrong_count: number
  train_count: number
  total_train_seconds: number
  curve_points: WordMemoryCurvePoint[]
  future_risk: MemoryFutureRiskPoint[]
}

export interface MemoryVisualization {
  curve_points: MemoryCurvePoint[]
  future_risk: MemoryFutureRiskPoint[]
  words: MemoryWordSummary[]
  graph: { nodes: MemoryGraphNode[]; links: MemoryGraphLink[] }
}

export interface TranslateResult {
  source_text: string
  target_text: string
  source_lang: string
  target_lang: string
  phonetic?: string
  example_en?: string
  example_cn?: string
  found: boolean
}

export interface QuizOption {
  label: string
  text: string
}

export interface QuizQuestion {
  word_id: number
  question_type: string
  prompt: string
  options: QuizOption[]
  correct_answer: string
  phonetic?: string
}

export type QuizTrack = 'accumulation' | 'book'

export interface QuizStats {
  total_words: number
  new_count: number
  learning_count: number
  mastered_count: number
  weak_count: number
  today_quiz_count: number
  today_correct_count: number
  today_accuracy: number
  daily_target: number
  today_completed: number
  streak_days: number
  track?: QuizTrack
  book_id?: number | null
}

export interface WordBook {
  id: number
  slug: string
  title: string
  description?: string | null
  level: string
  word_count: number
  unit_count: number
  sort_order: number
  daily_target: number
  master_required_count: number
  weak_wrong_threshold: number
  learn_mode: string
}

export interface WordBookProgress {
  book_id: number
  total: number
  introduced: number
  mastered: number
  learning: number
  locked: number
}

export interface BookPracticeSettings {
  book_id: number
  daily_target: number
  master_required_count: number
  weak_wrong_threshold: number
}

export interface ActiveBookState {
  book: WordBook | null
  progress: WordBookProgress | null
  settings?: BookPracticeSettings | null
}

export interface Settings {
  daily_target: number
  master_required_count: number
  weak_wrong_threshold: number
}

export interface UserProfile {
  id: number
  username: string
  created_at: string
}

export interface UserProfileUpdate {
  username?: string
  current_password?: string
  new_password?: string
}

export interface MemoryToken {
  role: string
  key: string
  label: string
  value: string
  revealed: boolean
}

export interface CoachWordBrief {
  word_id: number
  zh: string
  phonetic?: string | null
  retention_now: number
  mastery_score: number
  status: string
}

export interface CoachSessionResponse {
  words: CoachWordBrief[]
  total: number
}

export interface MemoryTransformerCurvePoint {
  hours_ahead: number
  recall_percent: number
  forgetting_percent: number
}

export interface MemoryTransformerAttention {
  index: number
  label: string
  weight: number
}

export interface MemoryTransformerPredict {
  word_id: number
  en: string
  recall_now_percent: number
  formula_recall_percent: number
  model_recall_percent: number
  blend_weight: number
  event_count: number
  model_trained: boolean
  recommended_review_days: number
  half_life_hours?: number | null
  curve: MemoryTransformerCurvePoint[]
  attention_hint: MemoryTransformerAttention[]
}

export interface CoachTurnResponse {
  assistant_messages: string[]
  tokens?: MemoryToken[]
  stage: string
  expect_input: boolean
  prompt_zh?: string
  prompt_phonetic?: string | null
  input_hint?: string
  is_correct?: boolean | null
  quiz_recorded: boolean
  word_complete: boolean
  hints_used: number
  target_en?: string | null
  target_zh?: string | null
}

export const api = {
  register: (username: string, password: string) =>
    request.post('/auth/register', { username, password }),
  login: (username: string, password: string, remember = true) =>
    request.post<{ access_token: string }>('/auth/login', { username, password, remember }),
  me: () => request.get<UserProfile>('/auth/me'),
  updateMe: (data: UserProfileUpdate) => request.patch<UserProfile>('/auth/me', data),
  translate: (text: string) => request.post<TranslateResult>('/translate', { text }),
  createWord: (data: Partial<Word>) => request.post<Word>('/words', data),
  listWords: (status?: string, bookId?: number) =>
    request.get<Word[]>('/words', {
      params: {
        ...(status ? { status } : {}),
        ...(bookId !== undefined ? { book_id: bookId } : {}),
      },
    }),
  getWord: (id: number) => request.get<Word>(`/words/${id}`),
  memoryViz: (bookId = 0) =>
    request.get<MemoryVisualization>('/words/memory-viz', { params: { book_id: bookId } }),
  listBooks: () => request.get<WordBook[]>('/books'),
  getActiveBook: () => request.get<ActiveBookState>('/books/active'),
  setActiveBook: (bookId: number) =>
    request.post<ActiveBookState>('/books/active', { book_id: bookId }),
  getBookSettings: () => request.get<BookPracticeSettings>('/books/settings'),
  updateBookSettings: (data: {
    book_id?: number
    daily_target?: number
    master_required_count?: number
    weak_wrong_threshold?: number
  }) => request.patch<ActiveBookState>('/books/settings', data),
  wordMemory: (id: number) => request.get<WordMemoryDetail>(`/words/${id}/memory`),
  wordMemoryModel: (id: number) =>
    request.get<MemoryTransformerPredict>(`/words/${id}/memory-model`),
  deleteWord: (id: number) => request.delete(`/words/${id}`),
  dailyQuiz: (track: QuizTrack = 'accumulation') =>
    request.get<{ questions: QuizQuestion[]; total: number; track: QuizTrack }>('/quiz/daily', {
      params: { track },
    }),
  spellQuiz: (track: QuizTrack = 'accumulation') =>
    request.get<{ questions: QuizQuestion[]; total: number; track: QuizTrack }>('/quiz/spell', {
      params: { track },
    }),
  submitAnswer: (data: {
    word_id: number
    question_type: string
    user_answer: string
    correct_answer: string
    duration_seconds?: number
  }) => request.post('/quiz/answer', data),
  quizStats: (track: QuizTrack = 'accumulation') =>
    request.get<QuizStats>('/quiz/stats', { params: { track } }),
  getSettings: () => request.get<Settings>('/settings'),
  updateSettings: (data: Partial<Settings>) => request.patch<Settings>('/settings', data),
  coachSession: (track: QuizTrack = 'accumulation') =>
    request.get<CoachSessionResponse>('/coach/session', { params: { track } }),
  coachTurn: (data: {
    word_id: number
    stage?: string
    user_message?: string
    hints_used?: number
    duration_seconds?: number
  }) => request.post<CoachTurnResponse>('/coach/turn', data),
}
