/**
 * Refresh Stamp — persisted record of when the AI care pass last COMPLETED.
 *
 * WHY (Bekky, 2026-09-03): the app should run the AI care pass (cohort care +
 * alert advice) exactly once per day, and only when it's actually needed. A
 * persisted stamp records when the pass last finished. On open:
 *   - If the stamp is fresh (same local day) → the pass already ran → SKIP.
 *   - If the stamp is stale/absent → run the pass → update the stamp on
 *     COMPLETION (not on start).
 *
 * The "update on completion" is the resilience guarantee: if the user opens,
 * the pass starts, and they close the app mid-flight, the stamp is NOT updated
 * → the next open sees a stale stamp → re-runs. So a care pass is never lost
 * to a mid-flight close; it just re-runs next open.
 *
 * The background task also updates the stamp when IT completes the pass, so a
 * background run "wins" for the day and the on-open pass skips.
 */
import * as FileSystem from 'expo-file-system';

const STAMP_PATH = () => `${FileSystem.documentDirectory || ''}pixiesprout-garden/ai-care-refresh-stamp.json`;

export type RefreshStamp = {
  /** ISO timestamp of the last COMPLETED care pass. */
  lastCompletedAt: string;
};

/** Read the persisted stamp. Returns null if absent/corrupt. */
export async function readRefreshStamp(): Promise<RefreshStamp | null> {
  try {
    if (!FileSystem.documentDirectory) return null;
    const info = await FileSystem.getInfoAsync(STAMP_PATH());
    if (!info.exists) return null;
    const raw = await FileSystem.readAsStringAsync(STAMP_PATH());
    const parsed = JSON.parse(raw) as RefreshStamp;
    if (parsed && typeof parsed.lastCompletedAt === 'string') return parsed;
    return null;
  } catch {
    return null;
  }
}

/** True if the stamp's lastCompletedAt falls on the same LOCAL calendar day as
 *  now — i.e. the care pass already ran today, so the on-open pass can skip. */
export function isStampFresh(stamp: RefreshStamp | null, now: Date = new Date()): boolean {
  if (!stamp || !stamp.lastCompletedAt) return false;
  const d = new Date(stamp.lastCompletedAt);
  if (Number.isNaN(d.getTime())) return false;
  return d.getFullYear() === now.getFullYear()
    && d.getMonth() === now.getMonth()
    && d.getDate() === now.getDate();
}

/** Persist the stamp with the given completion time (default: now). */
export async function markRefreshCompleted(at: string = new Date().toISOString()): Promise<void> {
  try {
    if (!FileSystem.documentDirectory) return;
    await FileSystem.makeDirectoryAsync(`${FileSystem.documentDirectory}pixiesprout-garden/`, { intermediates: true }).catch(() => {});
    await FileSystem.writeAsStringAsync(STAMP_PATH(), JSON.stringify({ lastCompletedAt: at } satisfies RefreshStamp));
  } catch {
    // Best-effort — a failed stamp write never blocks the app.
  }
}
