/**
 * Scheduled task management via platform IPC.
 */
import fs from "fs";
import path from "path";
import { getContext } from "../client.js";
import { writeIpcFile } from "../ipc.js";

export interface Task {
  id: string;
  groupFolder: string;
  prompt: string;
  scheduleType: "cron" | "interval" | "once";
  scheduleValue: string;
  status: "active" | "paused" | "completed";
  nextRun: string | null;
}

export async function listTasks(): Promise<Task[]> {
  const ctx = getContext();
  const file = path.join(ctx.ipcDir, "current_tasks.json");
  if (!fs.existsSync(file)) return [];
  return JSON.parse(fs.readFileSync(file, "utf8")) as Task[];
}

function groupFolder(): string {
  return process.env.NANOCLAW_GROUP_FOLDER ?? "";
}

function tasksDir(ipcDir: string): string {
  return path.join(ipcDir, "tasks");
}

export async function scheduleTask(
  params: {
    prompt: string;
    scheduleType: "cron" | "interval" | "once";
    scheduleValue: string;
    contextMode?: "group" | "isolated";
  },
  ipcDir?: string
): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), {
    type: "schedule_task",
    prompt: params.prompt,
    schedule_type: params.scheduleType,
    schedule_value: params.scheduleValue,
    context_mode: params.contextMode,
    targetJid: process.env.NANOCLAW_CHAT_JID,
    groupFolder: groupFolder(),
  });
}

export async function pauseTask(taskId: string, ipcDir?: string): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), { type: "pause_task", id: taskId, groupFolder: groupFolder() });
}

export async function resumeTask(taskId: string, ipcDir?: string): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), { type: "resume_task", id: taskId, groupFolder: groupFolder() });
}

export async function cancelTask(taskId: string, ipcDir?: string): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), { type: "cancel_task", id: taskId, groupFolder: groupFolder() });
}

export async function updateTask(
  taskId: string,
  params: { prompt?: string; scheduleType?: string; scheduleValue?: string },
  ipcDir?: string
): Promise<void> {
  const dir = ipcDir ?? getContext().ipcDir;
  writeIpcFile(tasksDir(dir), {
    type: "update_task",
    id: taskId,
    ...params,
    groupFolder: groupFolder(),
  });
}
