/**
 * User-authored tasks. Live alongside auto-scanned MEMORY.md items in
 * /api/now and share the same resolve/postpone flow.
 *
 * Storage: MANUAL_TASKS_FILE (JSON array). Each task has a stable id
 * (uuid) so it survives reorders and renames.
 *
 * Item key convention (for resolve/postpone matching) maps to
 * "manual_tasks.json:1|<text-prefix>" — same as scanned items, with
 * "manual_tasks.json" as the synthetic file name.
 */
import { readFileSync, writeFileSync, existsSync } from "node:fs";
import { MANUAL_TASKS_FILE } from "./paths";

export type ManualTask = {
  id: string;
  text: string;
  /** ISO date YYYY-MM-DD; absent = no firm date (will render as "open"). */
  due?: string;
  /** ISO date when added. */
  createdAt: string;
};

export function loadManualTasks(): ManualTask[] {
  if (!existsSync(MANUAL_TASKS_FILE)) return [];
  try {
    const data = JSON.parse(readFileSync(MANUAL_TASKS_FILE, "utf8"));
    return Array.isArray(data) ? data : [];
  } catch { return []; }
}

export function saveManualTasks(list: ManualTask[]) {
  writeFileSync(MANUAL_TASKS_FILE, JSON.stringify(list, null, 2));
}

/** Classify a task by its due date relative to today. Mirrors how
 *  scanned items are bucketed in now.ts. */
export function classifyTask(task: ManualTask, todayMs: number): "overdue" | "today" | "upcoming" | "open" {
  if (!task.due) return "open";
  const dueMs = new Date(task.due).setHours(0, 0, 0, 0);
  if (isNaN(dueMs)) return "open";
  const days = Math.round((dueMs - todayMs) / 86_400_000);
  if (days < 0) return "overdue";
  if (days === 0) return "today";
  if (days <= 14) return "upcoming";
  return "open";
}
