'use strict';

const fs = require('fs');
const path = require('path');
const os = require('os');

const PROFILE_DIR = path.join(os.homedir(), 'Library', 'Application Support', 'VoiceInput');
const PROFILE_FILE = path.join(PROFILE_DIR, 'user_profile.json');

const VALID_FIELDS = ['assistant_name', 'user_name', 'assistant_tone'];

function ensureDir() {
  if (!fs.existsSync(PROFILE_DIR)) {
    fs.mkdirSync(PROFILE_DIR, { recursive: true });
  }
}

function loadProfile() {
  ensureDir();
  if (!fs.existsSync(PROFILE_FILE)) {
    return {};
  }
  try {
    return JSON.parse(fs.readFileSync(PROFILE_FILE, 'utf8'));
  } catch (_) {
    return {};
  }
}

function saveProfile(profile) {
  ensureDir();
  fs.writeFileSync(PROFILE_FILE, JSON.stringify(profile, null, 2), 'utf8');
}

function setIdentityTool(args) {
  const profile = loadProfile();
  const changes = [];

  for (const field of VALID_FIELDS) {
    if (args[field] !== undefined && args[field] !== null) {
      const value = String(args[field]).trim();
      if (value) {
        const old = profile[field] || '';
        profile[field] = value;
        changes.push({ field, old, new: value });
      }
    }
  }

  if (changes.length === 0) {
    return { success: false, error: '请至少提供一个字段：assistant_name / user_name / assistant_tone' };
  }

  saveProfile(profile);

  return {
    success: true,
    changes,
    profile,
  };
}

module.exports = { setIdentityTool };
