import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { LlmConfig } from '@/lib/llm/types';

interface AssistantState extends LlmConfig {
  setConfig: (patch: Partial<LlmConfig>) => void;
  reset: () => void;
}

const DEFAULTS: LlmConfig = {
  enabled: false,
  provider: 'anthropic',
  model: 'claude-opus-4-8',
  baseUrl: 'https://api.anthropic.com',
  apiKey: '',
  rememberKey: true,
};

export const useAssistantStore = create<AssistantState>()(
  persist(
    (set) => ({
      ...DEFAULTS,
      setConfig: (patch) => set(patch),
      reset: () => set(DEFAULTS),
    }),
    {
      name: 'ttrpg-assistant',
      // Persist everything EXCEPT the key when the user opts out of remembering it.
      // The key then lives in memory for the tab only and is re-entered each launch.
      partialize: (state) => {
        const { setConfig, reset, apiKey, rememberKey, ...rest } = state;
        void setConfig;
        void reset;
        return rememberKey ? { ...rest, apiKey, rememberKey } : { ...rest, rememberKey };
      },
    },
  ),
);

/** Non-hook accessor for code outside React (mirrors the LlmConfig shape). */
export function getLlmConfig(): LlmConfig {
  const s = useAssistantStore.getState();
  return {
    enabled: s.enabled,
    provider: s.provider,
    model: s.model,
    baseUrl: s.baseUrl,
    apiKey: s.apiKey,
    rememberKey: s.rememberKey,
  };
}
