import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { storage } from '@/services/storage'

export type AIProvider = 'openrouter' | 'minimax' | 'opencode'
export type ModelTier = 'free' | 'cheap' | 'premium'

export interface AIModel {
  id: string
  label: string
  provider: AIProvider
  tier: ModelTier
}

export const AVAILABLE_MODELS: AIModel[] = [
  { id: 'deepseek/deepseek-chat-v3-0324:free', label: 'DeepSeek V3 (free)', provider: 'openrouter', tier: 'free' },
  { id: 'deepseek/deepseek-r1:free', label: 'DeepSeek R1 (free)', provider: 'openrouter', tier: 'free' },
  { id: 'openai/gpt-4o-mini', label: 'GPT-4o Mini', provider: 'openrouter', tier: 'cheap' },
  { id: 'google/gemini-2.0-flash-001', label: 'Gemini 2.0 Flash', provider: 'openrouter', tier: 'cheap' },
  { id: 'openai/gpt-4o', label: 'GPT-4o', provider: 'openrouter', tier: 'premium' },
  { id: 'anthropic/claude-sonnet-4', label: 'Claude Sonnet 4', provider: 'openrouter', tier: 'premium' },
  { id: 'meta-llama/llama-4-maverick', label: 'Llama 4 Maverick', provider: 'openrouter', tier: 'free' },
  { id: 'MiniMax-M2.7', label: 'MiniMax M2.7', provider: 'minimax', tier: 'free' },
  { id: 'MiniMax-M2.7-highspeed', label: 'MiniMax M2.7 HighSpeed', provider: 'minimax', tier: 'free' },
  { id: 'MiniMax-M2.5', label: 'MiniMax M2.5', provider: 'minimax', tier: 'free' },
  { id: 'MiniMax-M2.5-highspeed', label: 'MiniMax M2.5 HighSpeed', provider: 'minimax', tier: 'free' },
  { id: 'MiniMax-M2.1', label: 'MiniMax M2.1', provider: 'minimax', tier: 'free' },
  { id: 'MiniMax-M2.1-highspeed', label: 'MiniMax M2.1 HighSpeed', provider: 'minimax', tier: 'free' },
  { id: 'MiniMax-M2', label: 'MiniMax M2', provider: 'minimax', tier: 'free' },
]

export interface ProviderConfig {
  label: string
  descKey: string
  badgeKey?: string
  apiKeyHelp: string
  apiKeyLink?: string
  baseUrl: string
}

export const PROVIDER_CONFIG: Record<AIProvider, ProviderConfig> = {
  openrouter: {
    label: 'OpenRouter',
    descKey: 'settings.openrouterDesc',
    badgeKey: 'settings.recommended',
    apiKeyHelp: 'settings.keyHelp',
    apiKeyLink: 'https://openrouter.ai/keys',
    baseUrl: 'https://openrouter.ai/api/v1/chat/completions',
  },
  minimax: {
    label: 'MiniMax',
    descKey: 'settings.minimaxDesc',
    apiKeyHelp: 'settings.minimaxKeyHelp',
    apiKeyLink: 'https://platform.minimax.io/user-center/basic-information/interface-key',
    baseUrl: '/api/proxy/minimax',
  },
  opencode: {
    label: 'OpenCode',
    descKey: 'settings.opencodeDesc',
    badgeKey: 'settings.bridge',
    apiKeyHelp: 'settings.opencodeInfoDesc',
    baseUrl: '',
  },
}

const SETTINGS_KEY = 'alpha_settings'
const API_KEY_PREFIX = 'ai_key_'

export function getProviderApiKey(provider: AIProvider): string {
  return storage.get(`${API_KEY_PREFIX}${provider}`) || ''
}

export function setProviderApiKey(provider: AIProvider, key: string) {
  storage.set(`${API_KEY_PREFIX}${provider}`, key)
}

export function hasProviderApiKey(provider: AIProvider): boolean {
  return !!getProviderApiKey(provider)
}

export function removeProviderApiKey(provider: AIProvider) {
  storage.remove(`${API_KEY_PREFIX}${provider}`)
}

// ─── MiniMax group_id ──────────────────────────────────────

export function getMinimaxGroupId(): string {
  return storage.get('minimax_group_id') || ''
}

export function setMinimaxGroupId(id: string) {
  storage.set('minimax_group_id', id)
}

export const useSettingsStore = defineStore('settings', () => {
  const saved = storage.getJSON<{ provider: AIProvider; modelId: string }>(SETTINGS_KEY) || {
    provider: 'openrouter' as AIProvider,
    modelId: 'deepseek/deepseek-chat-v3-0324:free',
  }

  const provider = ref<AIProvider>(saved.provider)
  let initialModel = saved.modelId
  let migrated = false
  // Migración: modelos viejos eliminados del catálogo → M2.7
  const OLD_MINIMAX_MODELS = ['minimax-text-01', 'abab5.5s', 'abab6.5s', 'abab6.5g']
  if (provider.value === 'minimax' && OLD_MINIMAX_MODELS.includes(initialModel)) {
    initialModel = 'MiniMax-M2.7'
    migrated = true
  }
  // Si el modelo guardado ya no existe, migrar al primero del provider
  if (!AVAILABLE_MODELS.find(m => m.id === initialModel)) {
    const fallback = AVAILABLE_MODELS.find(m => m.provider === provider.value)
    if (fallback) { initialModel = fallback.id; migrated = true }
  }
  const modelId = ref<string>(initialModel)
  if (migrated) {
    storage.setJSON(SETTINGS_KEY, { provider: provider.value, modelId: initialModel })
  }
  const keyVersion = ref(0)
  const minimaxGroupId = ref<string>(storage.get('minimax_group_id') || '')

  const selectedModel = computed(() =>
    AVAILABLE_MODELS.find(m => m.id === modelId.value) ?? null
  )

  const activeProviderConfig = computed(() => PROVIDER_CONFIG[provider.value])

  const apiKeyConfigured = computed(() => {
    keyVersion.value
    return hasProviderApiKey(provider.value)
  })

  const freeModels = computed(() =>
    AVAILABLE_MODELS.filter(m => m.provider === provider.value && m.tier === 'free')
  )
  const cheapModels = computed(() =>
    AVAILABLE_MODELS.filter(m => m.provider === provider.value && m.tier === 'cheap')
  )
  const premiumModels = computed(() =>
    AVAILABLE_MODELS.filter(m => m.provider === provider.value && m.tier === 'premium')
  )
  const allModelsForProvider = computed(() =>
    AVAILABLE_MODELS.filter(m => m.provider === provider.value)
  )

  function setActiveProvider(p: AIProvider) {
    provider.value = p
    keyVersion.value++
    const models = AVAILABLE_MODELS.filter(m => m.provider === p)
    if (models.length > 0 && !models.find(m => m.id === modelId.value)) {
      modelId.value = models[0].id
    }
    persist()
  }

  function setModel(id: string) {
    modelId.value = id
    persist()
  }

  function saveApiKey(key: string) {
    setProviderApiKey(provider.value, key)
    keyVersion.value++
  }

  function removeKey() {
    removeProviderApiKey(provider.value)
    keyVersion.value++
  }

  function saveMinimaxGroupId(id: string) {
    minimaxGroupId.value = id
    setMinimaxGroupId(id)
  }

  function persist() {
    storage.setJSON(SETTINGS_KEY, {
      provider: provider.value,
      modelId: modelId.value,
    })
  }

  return {
    provider,
    modelId,
    minimaxGroupId,
    selectedModel,
    activeProviderConfig,
    apiKeyConfigured,
    freeModels,
    cheapModels,
    premiumModels,
    allModelsForProvider,
    setActiveProvider,
    setModel,
    saveApiKey,
    removeKey,
    saveMinimaxGroupId,
  }
})
