import { create } from 'zustand';
import { DEFAULT_DEDUP_CONFIG, type DedupConfig } from '../domain/transaction/dedup';
import { DEFAULT_TRANSFER_CONFIG, type TransferConfig } from '../domain/transaction/transferRecognizer';

/**
 * 设置状态管理（plan.md「0.1 状态管理」settingsStore）。
 *
 * 持久化策略：内存状态 + 持久化钩子（persistTo）。生产环境传入 AsyncStorage 持久化，
 * 测试环境不传（纯内存）。这样避免直接依赖 @react-native-async-storage/async-storage，
 * 使本 store 可单测。
 */

export type ThemeMode = 'light' | 'dark' | 'system';
export type Locale = 'zh' | 'en';

export interface SettingsState {
  // 去重/转账配置（影响 BillPipeline）
  dedupConfig: DedupConfig;
  transferConfig: TransferConfig;
  /** 是否启用多通道联合去重。 */
  dedupEnabled: boolean;
  /** 是否启用转账智能识别。 */
  transferRecognitionEnabled: boolean;

  // UI 偏好
  themeMode: ThemeMode;
  locale: Locale;
  /** 应用锁启用。 */
  appLockEnabled: boolean;
  /** 引导是否完成。 */
  onboardingCompleted: boolean;
  setOnboardingCompleted: (v: boolean) => void;
  setLayer1RuleEnabled: (enabled: boolean) => void;
  setLayer2OcrEnabled: (enabled: boolean) => void;
  setLayer3AiEnabled: (enabled: boolean) => void;
  setOcrModelVersion: (version: string) => void;
  setOcrModelDir: (dir: string) => void;

  // Sync Configurations
  webdavUrl?: string;
  webdavUsername?: string;
  webdavPassword?: string;
  webdavRemotePath?: string;
  gitRemoteUrl?: string;
  gitBranch?: string;
  gitUsername?: string;
  gitPassword?: string;

  // AI Configurations
  aiEnabled: boolean;
  aiProviderId: 'openai' | 'gemini' | 'deepseek';
  aiApiKey?: string;
  aiBaseUrl?: string;
  aiModel?: string;

  // Reminder Configurations
  reminderEnabled: boolean;
  reminderHour: number;
  reminderMinute: number;

  // 悬浮球
  floatingBallEnabled: boolean;
  setFloatingBallEnabled: (enabled: boolean) => void;

  // 自动记账层级
  /** 自动记账 L1：正则规则匹配。 */
  layer1RuleEnabled: boolean;
  /** 自动记账 L2：本地 OCR 识别。 */
  layer2OcrEnabled: boolean;
  /** 自动记账 L3：云端 AI Vision。 */
  layer3AiEnabled: boolean;
  /** OCR 模型版本（已下载），空字符串表示未安装。 */
  ocrModelVersion: string;
  /** OCR 模型文件目录的绝对路径。 */
  ocrModelDir: string;

  // 记账面板
  /** ＋按钮是否打开全局记账面板（P5 起默认 true；已持久化 false 的用户保持关闭）。 */
  numpadGlobalEntry: boolean;
  setNumpadGlobalEntry: (enabled: boolean) => void;
  /** 上次记账的资金账户（NumpadSheet 默认选中）。 */
  lastUsedAccount: string | null;
  /** 上次使用的分类 id。 */
  lastUsedCategoryId: string | null;
  setLastUsedEntry: (account: string | null, categoryId: string | null) => void;

  // actions
  updateDedupConfig: (patch: Partial<DedupConfig>) => void;
  updateTransferConfig: (patch: Partial<TransferConfig>) => void;
  setDedupEnabled: (enabled: boolean) => void;
  setTransferRecognitionEnabled: (enabled: boolean) => void;
  setThemeMode: (mode: ThemeMode) => void;
  setLocale: (locale: Locale) => void;
  setAppLockEnabled: (enabled: boolean) => void;
  updateSyncConfig: (patch: Partial<Pick<SettingsState, 'webdavUrl' | 'webdavUsername' | 'webdavPassword' | 'webdavRemotePath' | 'gitRemoteUrl' | 'gitBranch' | 'gitUsername' | 'gitPassword'>>) => void;
  updateAiConfig: (patch: Partial<Pick<SettingsState, 'aiEnabled' | 'aiProviderId' | 'aiApiKey' | 'aiBaseUrl' | 'aiModel'>>) => void;
  updateReminderConfig: (patch: Partial<Pick<SettingsState, 'reminderEnabled' | 'reminderHour' | 'reminderMinute'>>) => void;
  /** 最近搜索关键词（去重置顶，最多 8 条） */
  recentSearches: string[];
  addRecentSearch: (keyword: string) => void;
  clearRecentSearches: () => void;

  /** 持久化钩子（每次状态变更后调用，生产环境传 AsyncStorage 写入）。 */
  persistTo?: (state: PersistableSettings) => void;
  /** 从持久化源恢复（启动时调用）。 */
  hydrate: (data: Partial<PersistableSettings>) => void;
  /** 跳过下次持久化（hydrate 时使用）。 */
  skipPersist: boolean;
}

/** 可持久化的设置子集（排除函数）。 */
export interface PersistableSettings {
  dedupConfig: DedupConfig;
  transferConfig: TransferConfig;
  dedupEnabled: boolean;
  transferRecognitionEnabled: boolean;
  themeMode: ThemeMode;
  locale: Locale;
  appLockEnabled: boolean;
  webdavUrl?: string;
  webdavUsername?: string;
  webdavPassword?: string;
  webdavRemotePath?: string;
  gitRemoteUrl?: string;
  gitBranch?: string;
  gitUsername?: string;
  gitPassword?: string;
  onboardingCompleted: boolean;
  aiEnabled: boolean;
  aiProviderId: 'openai' | 'gemini' | 'deepseek';
  aiApiKey?: string;
  aiBaseUrl?: string;
  aiModel?: string;
  reminderEnabled: boolean;
  reminderHour: number;
  reminderMinute: number;
  floatingBallEnabled: boolean;
  numpadGlobalEntry: boolean;
  lastUsedAccount: string | null;
  lastUsedCategoryId: string | null;
  layer1RuleEnabled: boolean;
  layer2OcrEnabled: boolean;
  layer3AiEnabled: boolean;
  ocrModelVersion: string;
  ocrModelDir: string;
  recentSearches: string[];
}

/**
 * 敏感字段：这些值不写入明文 settings.json，由 storePersistence 层
 * 通过 expo-secure-store（Android Keystore / iOS Keychain）加密存储。
 */
export const SECURE_KEYS = ['aiApiKey', 'webdavPassword', 'gitPassword'] as const;
export type SecureKey = (typeof SECURE_KEYS)[number];

const DEFAULTS: PersistableSettings & { skipPersist: boolean; floatingBallEnabled: boolean } = {
  dedupConfig: DEFAULT_DEDUP_CONFIG,
  transferConfig: DEFAULT_TRANSFER_CONFIG,
  dedupEnabled: true,
  transferRecognitionEnabled: true,
  themeMode: 'system',
  locale: 'zh',
  appLockEnabled: false,
  webdavUrl: '',
  webdavUsername: '',
  webdavPassword: '',
  webdavRemotePath: 'main.bean',
  gitRemoteUrl: '',
  gitBranch: 'main',
  gitUsername: '',
  gitPassword: '',
  onboardingCompleted: false,
  aiEnabled: false,
  aiProviderId: 'openai',
  aiApiKey: '',
  aiBaseUrl: 'https://api.openai.com/v1',
  aiModel: 'gpt-4o-mini',
  reminderEnabled: false,
  reminderHour: 20,
  reminderMinute: 0,
  floatingBallEnabled: false,
  // P5 翻默认：＋按钮默认打开全局记账面板。
  // 注意：hydrate 以持久化值覆盖 DEFAULTS，已持久化 false 的老用户不受影响，仅新安装生效。
  numpadGlobalEntry: true,
  lastUsedAccount: null,
  lastUsedCategoryId: null,
  layer1RuleEnabled: true,
  layer2OcrEnabled: true,
  layer3AiEnabled: false,
  ocrModelVersion: '',
  ocrModelDir: '',
  recentSearches: [],
  skipPersist: false,
};

export function toPersistable(state: SettingsState): PersistableSettings {
  return {
    dedupConfig: state.dedupConfig,
    transferConfig: state.transferConfig,
    dedupEnabled: state.dedupEnabled,
    transferRecognitionEnabled: state.transferRecognitionEnabled,
    themeMode: state.themeMode,
    locale: state.locale,
    appLockEnabled: state.appLockEnabled,
    webdavUrl: state.webdavUrl,
    webdavUsername: state.webdavUsername,
    webdavPassword: state.webdavPassword,
    webdavRemotePath: state.webdavRemotePath,
    gitRemoteUrl: state.gitRemoteUrl,
    gitBranch: state.gitBranch,
    gitUsername: state.gitUsername,
    gitPassword: state.gitPassword,
    onboardingCompleted: state.onboardingCompleted,
    aiEnabled: state.aiEnabled,
    aiProviderId: state.aiProviderId,
    aiApiKey: state.aiApiKey,
    aiBaseUrl: state.aiBaseUrl,
    aiModel: state.aiModel,
    reminderEnabled: state.reminderEnabled,
    reminderHour: state.reminderHour,
    reminderMinute: state.reminderMinute,
    floatingBallEnabled: state.floatingBallEnabled,
    numpadGlobalEntry: state.numpadGlobalEntry,
    lastUsedAccount: state.lastUsedAccount,
    lastUsedCategoryId: state.lastUsedCategoryId,
    layer1RuleEnabled: state.layer1RuleEnabled,
    layer2OcrEnabled: state.layer2OcrEnabled,
    layer3AiEnabled: state.layer3AiEnabled,
    ocrModelVersion: state.ocrModelVersion,
    ocrModelDir: state.ocrModelDir,
    recentSearches: state.recentSearches,
  };
}

import { logger } from '../utils/logger';


export const useSettingsStore = create<SettingsState>((set) => ({
  ...DEFAULTS,

  addRecentSearch: (keyword) => {
    const kw = keyword.trim();
    if (!kw) return;
    set(state => ({ recentSearches: [kw, ...state.recentSearches.filter(s => s !== kw)].slice(0, 8) }));
  },
  clearRecentSearches: () => set({ recentSearches: [] }),

  updateDedupConfig: (patch) => {
    logger.info('settings', '更新去重配置', patch);
    set((s) => ({ dedupConfig: { ...s.dedupConfig, ...patch } }));
  },

  updateTransferConfig: (patch) => {
    logger.info('settings', '更新转账识别配置', patch);
    set((s) => ({ transferConfig: { ...s.transferConfig, ...patch } }));
  },

  setDedupEnabled: (enabled) => {
    logger.info('settings', `设置自动去重功能状态: ${enabled ? '开启' : '关闭'}`);
    set({ dedupEnabled: enabled });
  },

  setTransferRecognitionEnabled: (enabled) => {
    logger.info('settings', `设置转账识别功能状态: ${enabled ? '开启' : '关闭'}`);
    set({ transferRecognitionEnabled: enabled });
  },

  setThemeMode: (mode) => {
    logger.info('settings', `切换主题模式: ${mode}`);
    set({ themeMode: mode });
  },

  setLocale: (locale) => {
    logger.info('settings', `切换应用语言: ${locale}`);
    set({ locale });
  },

  setAppLockEnabled: (enabled) => {
    logger.info('settings', `设置应用锁安全防护: ${enabled ? '开启' : '关闭'}`);
    set({ appLockEnabled: enabled });
  },

  updateSyncConfig: (patch) => {
    const safePatch = { ...patch };
    if (safePatch.webdavPassword) safePatch.webdavPassword = '***';
    if (safePatch.gitPassword) safePatch.gitPassword = '***';
    logger.info('settings', '更新云同步配置', safePatch);
    set((s) => ({ ...s, ...patch }));
  },

  updateAiConfig: (patch) => {
    const safePatch = { ...patch };
    if (safePatch.aiApiKey) safePatch.aiApiKey = '***';
    logger.info('settings', '更新 AI 智记配置', safePatch);
    set((s) => ({ ...s, ...patch }));
  },

  updateReminderConfig: (patch) => {
    logger.info('settings', '更新记账提醒配置', patch);
    set((s) => ({ ...s, ...patch }));
  },

  setOnboardingCompleted: (completed) => {
    logger.info('settings', `设置新手引导完成状态: ${completed}`);
    set({ onboardingCompleted: completed });
  },

  setFloatingBallEnabled: (enabled) => {
    logger.info('settings', `设置桌面悬浮球: ${enabled ? '开启' : '关闭'}`);
    set({ floatingBallEnabled: enabled });
  },

  setNumpadGlobalEntry: (enabled) => {
    logger.info('settings', `设置全局记账小键盘: ${enabled ? '开启' : '关闭'}`);
    set({ numpadGlobalEntry: enabled });
  },

  setLastUsedEntry: (account, categoryId) => set({ lastUsedAccount: account, lastUsedCategoryId: categoryId }),

  setLayer1RuleEnabled: (enabled) => set({ layer1RuleEnabled: enabled }),

  setLayer2OcrEnabled: (enabled) => set({ layer2OcrEnabled: enabled }),

  setLayer3AiEnabled: (enabled) => set({ layer3AiEnabled: enabled }),

  setOcrModelVersion: (version) => set({ ocrModelVersion: version }),

  setOcrModelDir: (dir) => set({ ocrModelDir: dir }),

  hydrate: (data) => {
    // hydrate 期间跳过自动持久化
    // 使用单次 setState 合并所有数据，避免多次触发 subscriber
    // skipPersist 在同一次更新中设为 true 后立即还原，利用 zustand 同步通知特性，
    // subscriber 在批量更新结束后才触发，此时 skipPersist 已为 false 但内容未变，
    // storePersistence 的深比较会跳过实际写入。
    useSettingsStore.setState({ ...DEFAULTS, ...data, skipPersist: false });
  },
}));
