// PRE Web GUI — Quick Actions
// Configurable one-tap shortcut buttons above the chat input.
// Each action is a pre-filled prompt sent on click.
// Stored in ~/.pre/quick-actions.json.

const fs = require('fs');
const crypto = require('crypto');
const { QUICK_ACTIONS_FILE } = require('./constants');

// ── Default actions (created on first load if file doesn't exist) ───────────

const DEFAULT_ACTIONS = [
  {
    id: _id(),
    label: 'Morning Briefing',
    icon: '☀️',
    prompt: 'Give me a morning briefing: check my calendar for today, summarize any important unread emails, and tell me the weather.',
    enabled: true,
  },
  {
    id: _id(),
    label: 'Unread Emails',
    icon: '✉️',
    prompt: 'Check my email and summarize any unread messages, highlighting anything urgent.',
    enabled: true,
  },
  {
    id: _id(),
    label: "Today's Calendar",
    icon: '📅',
    prompt: "What's on my calendar today? List all events with times.",
    enabled: true,
  },
  {
    id: _id(),
    label: 'GitHub Activity',
    icon: '🔔',
    prompt: 'Check my GitHub notifications and summarize any PRs, issues, or mentions that need my attention.',
    enabled: true,
  },
  {
    id: _id(),
    label: 'Summarize Page',
    icon: '📄',
    prompt: 'Summarize the web page I have open in my browser.',
    enabled: true,
  },
];

// ── Persistence ─────────────────────────────────────────────────────────────

function load() {
  try {
    const data = JSON.parse(fs.readFileSync(QUICK_ACTIONS_FILE, 'utf-8'));
    return Array.isArray(data) ? data : [];
  } catch {
    // First run — write defaults
    save(DEFAULT_ACTIONS);
    return [...DEFAULT_ACTIONS];
  }
}

function save(actions) {
  fs.writeFileSync(QUICK_ACTIONS_FILE, JSON.stringify(actions, null, 2));
}

// ── CRUD ────────────────────────────────────────────────────────────────────

function list() {
  return load();
}

function add(action) {
  const actions = load();
  const newAction = {
    id: _id(),
    label: action.label || 'New Action',
    icon: action.icon || '⚡',
    prompt: action.prompt || '',
    enabled: action.enabled !== false,
  };
  actions.push(newAction);
  save(actions);
  return newAction;
}

function update(id, changes) {
  const actions = load();
  const idx = actions.findIndex(a => a.id === id);
  if (idx === -1) return null;
  const allowed = ['label', 'icon', 'prompt', 'enabled'];
  for (const key of allowed) {
    if (changes[key] !== undefined) actions[idx][key] = changes[key];
  }
  save(actions);
  return actions[idx];
}

function remove(id) {
  const actions = load();
  const filtered = actions.filter(a => a.id !== id);
  if (filtered.length === actions.length) return false;
  save(filtered);
  return true;
}

function reorder(ids) {
  const actions = load();
  const map = new Map(actions.map(a => [a.id, a]));
  const reordered = [];
  for (const id of ids) {
    if (map.has(id)) {
      reordered.push(map.get(id));
      map.delete(id);
    }
  }
  // Append any actions not in the reorder list
  for (const remaining of map.values()) {
    reordered.push(remaining);
  }
  save(reordered);
  return reordered;
}

function resetDefaults() {
  const fresh = DEFAULT_ACTIONS.map(a => ({ ...a, id: _id() }));
  save(fresh);
  return fresh;
}

// ── Helpers ──────────────────────────────────────────────────────────────────

function _id() {
  return crypto.randomBytes(6).toString('hex');
}

module.exports = { list, add, update, remove, reorder, resetDefaults };
