import { ref } from 'vue';
import { defineStore } from 'pinia';
import { useLocalStorage } from '@vueuse/core';

export interface Language {
  displayName: string; // UI 显示的中文名，如 "英语（英国）"
  englishName: string; // 文件中的第二列，用于 {SOURCE_LANG}
  code: string;        // 文件中的第一列，用于 {SOURCE_CODE}
}

export const LANGUAGES: Language[] = [
  { displayName: '中文（简体）', englishName: 'Simplified Chinese', code: 'zh-Hans' },
  { displayName: '中文（繁体）', englishName: 'Traditional Chinese', code: 'zh-Hant' },
  { displayName: '英语（美国）', englishName: 'American English', code: 'en-US' },
  { displayName: '英语（英国）', englishName: 'British English', code: 'en-GB' },
  { displayName: '西班牙语', englishName: 'Spanish', code: 'es' },
  { displayName: '葡萄牙语', englishName: 'Portuguese', code: 'pt' },
  { displayName: '日语', englishName: 'Japanese', code: 'ja' },
  { displayName: '韩语', englishName: 'Korean', code: 'ko' },
  { displayName: '法语', englishName: 'French', code: 'fr' },
  { displayName: '德语', englishName: 'German', code: 'de' },
  { displayName: '意大利语', englishName: 'Italian', code: 'it' },
  { displayName: '俄语', englishName: 'Russian', code: 'ru' },
  { displayName: '越南语', englishName: 'Vietnamese', code: 'vi' },
  { displayName: '泰语', englishName: 'Thai', code: 'th' },
  { displayName: '阿拉伯语', englishName: 'Arabic', code: 'ar' },
];

export const SPEAKER_IDENTITY_OPTIONS = [
  { label: '男性', value: 'Male' },
  { label: '女性', value: 'Female' },
  { label: '中性', value: 'Gender-neutral' },
];

export const TONE_REGISTER_OPTIONS = [
  { label: '正式专业', value: 'Formal & Professional', description: '商务邮件、法律合同、官方报告' },
  { label: '礼貌客气', value: 'Polite & Respectful', description: '与长辈、客户或初次见面的人交流' },
  { label: '礼貌随和', value: 'Polite & Conversational', description: '得体但不刻板的日常对话' },
  { label: '中性标准', value: 'Neutral & Standard', description: '维基百科、说明书、客观的新闻报道' },
  { label: '非正式', value: 'Casual & Informal', description: '朋友聊天、社交媒体、非正式简讯' },
  { label: '亲切友好', value: 'Warm & Friendly', description: '社区信函、给朋友的建议、温馨提示' },
  { label: '严谨权威', value: 'Strict & Authoritative', description: '警示标志、强制规定、上级指令' },
  { label: '热情生动', value: 'Enthusiastic & Vivid', description: '广告文案、旅游推荐、博主推文' },
];

export const DEFAULT_TEMPLATE = `You are a professional {SOURCE_LANG} ({SOURCE_CODE}) to {TARGET_LANG} ({TARGET_CODE}) translator. Your goal is to accurately convey the meaning and nuances of the original {SOURCE_LANG} text while adhering to {TARGET_LANG} grammar, vocabulary, and cultural sensitivities.

[Constraints]
1. Speaker Identity: {SPEAKER_IDENTITY}. Ensure all grammatical agreements and self-referential terms in {TARGET_LANG} reflect this.
2. Tone & Register: {TONE_REGISTER}.
3. Produce ONLY the {TARGET_LANG} translation, without any additional explanations, notes, or commentary.
4. If [Context] is provided, use it strictly to disambiguate polysemous words. DO NOT add any factual information or descriptive details from the [Context] that are not present in the [Text to Translate].`;

export interface ApiProfile {
  id: string;
  name: string;
  apiBaseUrl: string;
  apiKey: string;
  modelName: string;
}

export const useSettingsStore = defineStore('settings', () => {
  const isDark = useLocalStorage('is-dark', false);
  const apiBaseUrl = useLocalStorage('api-base-url', 'http://localhost:11434/v1');
  const apiKey = useLocalStorage('api-key', '');
  const modelName = useLocalStorage('model-name', 'translategemma:12b');
  const profiles = useLocalStorage<ApiProfile[]>('api-profiles', []);
  const enableStreaming = useLocalStorage('enable-streaming', true);
  const systemPromptTemplate = useLocalStorage('system-prompt-template', DEFAULT_TEMPLATE);
  const context = useLocalStorage('translation-context', '');
  
  // 存储整个对象以保持一致性
  const sourceLang = useLocalStorage<Language>('source-lang-v2', LANGUAGES[0]);
  const targetLang = useLocalStorage<Language>('target-lang-v2', LANGUAGES[4]);

  const speakerIdentity = useLocalStorage('speaker-identity', SPEAKER_IDENTITY_OPTIONS[0].value);
  const toneRegister = useLocalStorage('tone-register', TONE_REGISTER_OPTIONS[2].value);

  const logs = ref<{ timestamp: string; type: 'request' | 'response' | 'error'; content: any }[]>([]);
  
  const addLog = (type: 'request' | 'response' | 'error', content: any) => {
    const now = new Date();
    const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    
    logs.value.unshift({
      timestamp,
      type,
      content
    });
    if (logs.value.length > 20) logs.value.pop();
  };

  return {
    isDark,
    apiBaseUrl,
    apiKey,
    modelName,
    profiles,
    enableStreaming,
    systemPromptTemplate,
    context,
    sourceLang,
    targetLang,
    speakerIdentity,
    toneRegister,
    logs,
    addLog
  };
});
