/**
 * EXPERIMENT(weighting) Phase 3 — action trace log.
 *
 * Records every outcome action Pavel takes on a surfaced thread:
 *   resolve   — item was completed / closed
 *   postpone  — item was snoozed (with days)
 *   work-on   — "Work on this" opened a chat for the item
 *
 * Each entry captures the item's weight and contributing signals at the
 * moment of action. Phase 4 calibration reads this log to compute:
 *   lift = P(resolve | signal=1) / P(resolve | signal=0)
 * per signal, then adjusts coefficients in computeWeight() accordingly.
 *
 * "ignore" (item surfaced but no action taken) is the implicit baseline —
 * any item that appears in a scan but has no action_log entry within N days
 * is treated as ignored. The observation window in Phase 3 is 14 days.
 */
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { ACTION_LOG_FILE } from "./paths";

export type ActionType = "resolve" | "postpone" | "work-on";

/** Snapshot of the signals that fed into computeWeight() for this item. */
export type WeightSnapshot = {
  weight: number;
  signals: {
    days_overdue: number;
    pavel_mention: 0 | 1;
    linear_comment_mention: 0 | 1;
    status_keywords: number;
    verdict_escalate: 0 | 1;
  };
  verdict: string | null;
};

export type ActionLogEntry = {
  itemKey: string;
  file: string;
  line: number;
  text: string;
  source: string;
  kind: string;
  action: ActionType;
  at: string; // ISO timestamp
  /** Populated when action = "postpone". */
  postponeDays?: number;
  /** Weight + signals at time of action — the ground truth for Phase 4. */
  weightSnapshot?: WeightSnapshot;
};

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

export function appendAction(entry: ActionLogEntry): void {
  const list = loadActionLog();
  list.push(entry);
  try {
    mkdirSync(dirname(ACTION_LOG_FILE), { recursive: true });
    writeFileSync(ACTION_LOG_FILE, JSON.stringify(list, null, 2));
  } catch (err) {
    console.error("[action-log] write failed:", err);
  }
}
