// PRE Web GUI — First-Run Onboarding
// Tracks whether the user has completed initial setup workflows.
// State stored in ~/.pre/onboarding.json.

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

const DEFAULT_STATE = {
  completedAt: null,
  dismissedAt: null,
  workflowsRun: [],
};

function load() {
  try {
    const data = JSON.parse(fs.readFileSync(ONBOARDING_FILE, 'utf-8'));
    return { ...DEFAULT_STATE, ...data };
  } catch {
    return { ...DEFAULT_STATE };
  }
}

function save(state) {
  fs.writeFileSync(ONBOARDING_FILE, JSON.stringify(state, null, 2));
}

function getState() {
  return load();
}

function isFirstRun() {
  const state = load();
  return !state.completedAt && !state.dismissedAt;
}

function markWorkflowRun(workflowId) {
  const state = load();
  if (!state.workflowsRun.includes(workflowId)) {
    state.workflowsRun.push(workflowId);
  }
  // Auto-complete after running any workflow
  if (!state.completedAt) {
    state.completedAt = new Date().toISOString();
  }
  save(state);
  return state;
}

function dismiss() {
  const state = load();
  state.dismissedAt = new Date().toISOString();
  save(state);
  return state;
}

function reset() {
  save({ ...DEFAULT_STATE });
  return { ...DEFAULT_STATE };
}

// ── Workflow templates ────────────────────────────────────────────────────────
// Each template is a curated prompt that configures PRE for daily use.

function getWorkflows(platform) {
  const isMac = platform === 'macos';
  return [
    {
      id: 'morning-routine',
      icon: '🌅',
      title: 'Set Up My Morning Routine',
      description: 'Schedule a daily briefing with calendar, email, and weather.',
      prompt: 'Set up a daily morning routine for me: schedule a cron job that runs every weekday at 8:00 AM to check my calendar for the day, summarize important unread emails, and give me the weather forecast. Name it "Morning Briefing".',
    },
    {
      id: 'file-organizer',
      icon: '📂',
      title: 'Organize My Files Automatically',
      description: 'Auto-sort downloads and index documents for search.',
      prompt: isMac
        ? 'Help me set up automatic file organization: (1) Create a scheduled job that runs every 2 hours to move documents from my ~/Downloads folder into ~/Documents, organized by file type. (2) Index my ~/Documents folder with RAG and call it "my-documents" so I can search it later.'
        : 'Help me set up automatic file organization: (1) Create a scheduled job that runs every 2 hours to move documents from my Downloads folder into Documents, organized by file type. (2) Index my Documents folder with RAG and call it "my-documents" so I can search it later.',
    },
    {
      id: 'work-dashboard',
      icon: '📊',
      title: 'Build My Work Dashboard',
      description: 'Create a live dashboard with calendar, tasks, and system stats.',
      prompt: 'Create a live work dashboard as an HTML artifact that shows: (1) today\'s calendar events, (2) my 5 most recent emails, (3) CPU and memory usage. Make it auto-refresh every 3 minutes. Use a clean, modern dark theme.',
    },
    {
      id: 'dinner-planner',
      icon: '🍽️',
      title: 'Schedule Daily Dinner Ideas',
      description: 'Get a new recipe every day at noon, customized for your family.',
      prompt: 'Schedule a daily cron job at 12:00 PM that suggests a dinner recipe for a family. Randomize the cuisine between Japanese, Vietnamese, Thai, Italian, and Mexican. Name it "Dinner Ideas".',
    },
    {
      id: 'email-monitor',
      icon: '📬',
      title: 'Set Up Email Monitoring',
      description: 'Get notified about urgent emails throughout the day.',
      prompt: 'Create a scheduled job that runs every 3 hours during business hours (9am-6pm, weekdays only) to check my email for anything urgent or requiring a response. Summarize only the important messages. Name it "Email Check".',
    },
    {
      id: 'full-assistant',
      icon: '🚀',
      title: 'Full Personal Assistant Setup',
      description: 'Morning briefing, file organizer, email alerts -- the complete package.',
      prompt: 'I want to set up PRE as my full personal assistant. Please configure: (1) A daily morning briefing at 8:00 AM weekdays that checks my calendar, summarizes unread emails, and gives the weather. (2) A downloads organizer that runs every 2 hours to sort files from Downloads into Documents. (3) An email check every 3 hours during business hours for urgent items. Set up all three as scheduled jobs.',
    },
  ];
}

module.exports = { getState, isFirstRun, markWorkflowRun, dismiss, reset, getWorkflows };
