'use strict';

const os = require('os');
const path = require('path');
const fs = require('fs');
const { execSync } = require('child_process');

function getTerminalType() {
  if (process.platform === 'win32') {
    if (process.env.PSModulePath || process.env.POWERSHELL_DISTRIBUTION_CHANNEL) return 'powershell';
    return 'cmd';
  }
  return 'terminal';
}

function getGitInfo(workspace) {
  try {
    const branch = execSync('git rev-parse --abbrev-ref HEAD', { cwd: workspace, stdio: ['ignore', 'pipe', 'ignore'] })
      .toString()
      .trim();
    if (!branch) return '未初始化';
    const status = execSync('git status --porcelain', { cwd: workspace, stdio: ['ignore', 'pipe', 'ignore'] })
      .toString()
      .trim();
    const dirty = status ? 'dirty' : 'clean';
    return `${branch} (${dirty})`;
  } catch (_) {
    return '未初始化';
  }
}

function loadUserProfile() {
  const profileDir = path.join(os.homedir(), 'Library', 'Application Support', 'VoiceInput');
  const profilePath = path.join(profileDir, 'user_profile.json');
  try {
    if (fs.existsSync(profilePath)) {
      const raw = fs.readFileSync(profilePath, 'utf8');
      const data = JSON.parse(raw);
      return {
        assistantName: data.assistant_name || 'AI助手未设置',
        assistantTone: data.assistant_tone || '语气未设置',
        userName: data.user_name || '用户未设置',
      };
    }
  } catch (_) { /* 忽略，使用默认值 */ }
  return {
    assistantName: 'AI助手未设置',
    assistantTone: '语气未设置',
    userName: '用户未设置',
  };
}

function buildSystemPrompt(basePrompt, opts) {
  const now = new Date();
  const localIso = `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}`;
  const platform = os.platform();
  const systemName = platform === 'darwin' ? 'macos' : platform === 'win32' ? 'windows' : 'linux';
  const profile = loadUserProfile();
  let prompt = basePrompt;
  const allowModeValue = opts.allowMode === 'read_only'
    ? `${opts.allowMode}\n  已禁用 edit_file、run_command。若用户要求使用，请告知当前无权限需要用户输入 /allow 切换权限。`
    : opts.allowMode;
  const replacements = {
    assistant_name: profile.assistantName,
    assistant_tone: profile.assistantTone,
    user_name: profile.userName,
    current_time: localIso,
    path: opts.workspace,
    workspace: opts.workspace,
    system: `${systemName} (${os.release()})`,
    terminal: getTerminalType(),
    allow_mode: allowModeValue,
    permissions: allowModeValue,
    git: getGitInfo(opts.workspace),
    model_id: opts.modelId || '',
    multimodal_ability: opts.multimodal_ability || '不可查看图片，不可查看视频',
  };
  for (const [key, value] of Object.entries(replacements)) {
    const token = `{${key}}`;
    prompt = prompt.split(token).join(String(value));
  }
  return prompt.trim();
}

module.exports = { buildSystemPrompt };
