#!/usr/bin/env node
// Publishing slots + work-in-progress view (N13 — A1-10).
//
// The week's production grid in one place: the slots the operator publishes in,
// what already covers them (the short-form queue + the editions register), and
// which long-form editions are still in flight. Session start reads it so the
// week is visible without opening a file; the commands read the SAME functions
// through `node --input-type=module -e` (the queue-manager.mjs pattern), so the
// vacancy the hook reports and the slot `/linkedin:newsletter` defaults to can
// never disagree.
//
// Zero-dep on purpose: this runs inside a SessionStart hook, which must not
// spawn tsx or touch node_modules (same discipline as session-start.mjs's direct
// trend-store read).
//
// DOMAIN-NEUTRAL: the plugin ships no publishing times. The grid lives in the
// per-user data dir (`profile/publishing-slots.json`); an absent config means
// silence, never a default schedule imposed on the user.
//
// The core is pure — dates in as `YYYY-MM-DD` strings, no clock — so vacancy is
// testable without freezing time. Only the thin readers below touch the disk.

import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { getDataRoot } from './data-root.mjs';

export const SLOTS_SCHEMA_VERSION = 1;

const MS_PER_DAY = 86400000;

// Canonical day keys (ISO-ish 3-letter, lowercase) → JS getUTCDay index.
const DAY_INDEX = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
const DAY_LABEL = { sun: 'Sun', mon: 'Mon', tue: 'Tue', wed: 'Wed', thu: 'Thu', fri: 'Fri', sat: 'Sat' };

// A queue entry counts as covering its date when it is still going out or has
// already gone out. A cancelled entry does NOT — that slot fell vacant again.
const COVERING_QUEUE_STATUS = new Set(['scheduled', 'published']);

const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/;

/** `${DATA}/profile/publishing-slots.json` — user config, survives reinstalls (M0). */
export function defaultSlotsPath() {
  return join(getDataRoot('profile'), 'publishing-slots.json');
}

/** `${DATA}/editions/register.json` — twin of scripts/editions/src/register.ts:defaultRegisterPath. */
export function defaultRegisterPath() {
  return join(getDataRoot('editions'), 'register.json');
}

/** `${DATA}/drafts/queue.json` — read directly (never via queue-manager's ensureQueue: a read-only check must not create files). */
function queuePath() {
  return join(getDataRoot('drafts'), 'queue.json');
}

function readJson(path) {
  if (!existsSync(path)) return null;
  try {
    return JSON.parse(readFileSync(path, 'utf-8'));
  } catch {
    return null;
  }
}

/**
 * Normalize a raw config into the grid the rest of the module speaks.
 * Forgiving by design: an unusable row is dropped, never thrown — a typo in a
 * config file must not take down session start.
 */
export function normalizeSlots(raw) {
  const timezone = typeof raw?.timezone === 'string' ? raw.timezone : '';
  const rows = Array.isArray(raw?.slots) ? raw.slots : [];
  const slots = [];
  for (const r of rows) {
    const day = String(r?.day ?? '').trim().toLowerCase().slice(0, 3);
    const time = String(r?.time ?? '').trim();
    if (!(day in DAY_INDEX) || !TIME_RE.test(time)) continue;
    slots.push({ day, time, label: typeof r?.label === 'string' ? r.label : '' });
  }
  return { timezone, slots };
}

/** Read the per-user grid. Absent/malformed ⇒ empty grid (silence, not a nag). */
export function readSlots(path = defaultSlotsPath()) {
  return normalizeSlots(readJson(path));
}

function addDays(dateStr, n) {
  // Noon UTC anchor — the codebase idiom (state-updater.mjs) that keeps date
  // arithmetic clear of DST edges.
  const d = new Date(`${dateStr}T12:00:00Z`);
  d.setUTCDate(d.getUTCDate() + n);
  return d.toISOString().slice(0, 10);
}

function weekdayKey(dateStr) {
  const idx = new Date(`${dateStr}T12:00:00Z`).getUTCDay();
  return Object.keys(DAY_INDEX).find((k) => DAY_INDEX[k] === idx) ?? '';
}

/**
 * Expand the weekly grid into concrete occurrences across `days` calendar days
 * starting at (and including) `from` — a slot today is still actionable.
 */
export function slotOccurrences(slots, from, days) {
  const out = [];
  for (let i = 0; i < days; i += 1) {
    const date = addDays(from, i);
    const key = weekdayKey(date);
    for (const s of slots) {
      if (s.day === key) out.push({ date, day: s.day, dayLabel: DAY_LABEL[s.day], time: s.time, label: s.label });
    }
  }
  return out.sort((a, b) => `${a.date} ${a.time}`.localeCompare(`${b.date} ${b.time}`));
}

/**
 * How many published/scheduled things land on each date — counted, not merely
 * flagged, so a day carrying two slots needs two posts to be full.
 */
export function coverageByDate(queueEntries, editionRows) {
  const counts = new Map();
  const bump = (date) => {
    if (!date) return;
    counts.set(date, (counts.get(date) ?? 0) + 1);
  };

  for (const e of queueEntries ?? []) {
    if (COVERING_QUEUE_STATUS.has(e?.status)) bump(e?.scheduled_date);
  }
  // Register rows carry `slot` as "YYYY-MM-DD HH:MM". Completed rows count too:
  // an edition that reached Step 10 IS the thing occupying that slot.
  for (const r of editionRows ?? []) {
    if (typeof r?.slot === 'string' && r.slot.length >= 10) bump(r.slot.slice(0, 10));
  }
  return counts;
}

/** The occurrences nothing covers, chronological. Per date, the earliest slots are considered filled first. */
export function vacantSlots(occurrences, coverage) {
  const remaining = new Map(coverage);
  const vacant = [];
  for (const occ of occurrences) {
    const left = remaining.get(occ.date) ?? 0;
    if (left > 0) remaining.set(occ.date, left - 1);
    else vacant.push(occ);
  }
  return vacant;
}

/** All register rows, whatever their status (coverage cares about completed ones too). */
export function readRegisterRows(path = defaultRegisterPath()) {
  const parsed = readJson(path);
  return Array.isArray(parsed?.editions) ? parsed.editions : [];
}

function readQueueEntries() {
  const parsed = readJson(queuePath());
  return Array.isArray(parsed?.queue) ? parsed.queue : [];
}

function todayISO() {
  return new Date().toISOString().slice(0, 10);
}

/** Every uncovered slot in the horizon — the vacancy warning's raw material. */
export function slotVacancies({ from = todayISO(), days = 14 } = {}) {
  const { slots } = readSlots();
  if (slots.length === 0) return [];
  const occurrences = slotOccurrences(slots, from, days);
  return vacantSlots(occurrences, coverageByDate(readQueueEntries(), readRegisterRows()));
}

/** The slot `/linkedin:newsletter` Step 10 defaults to; null when nothing is configured or everything is covered. */
export function nextFreeSlot(options = {}) {
  return slotVacancies(options)[0] ?? null;
}

/**
 * Editions in production right now, with whole days in flight (the `daysSince`
 * idiom the hook already reports elapsed time with). Deterministic order —
 * series, then edition id — mirroring listEditions in scripts/editions.
 */
export function activeEditions({ now = new Date().toISOString() } = {}) {
  const nowMs = Date.parse(now);
  return readRegisterRows()
    .filter((r) => r?.status === 'active')
    .sort((a, b) => String(a.series).localeCompare(String(b.series)) || String(a.editionId).localeCompare(String(b.editionId)))
    .map((r) => {
      const started = Date.parse(r?.startedAt ?? '');
      const daysInFlight =
        Number.isNaN(started) || Number.isNaN(nowMs) ? null : Math.floor((nowMs - started) / MS_PER_DAY);
      return { ...r, daysInFlight };
    });
}

/** "today" / "tomorrow" / "in N days" — how far off a slot is, in words. */
export function daysUntil(from, date) {
  const a = Date.parse(`${from}T12:00:00Z`);
  const b = Date.parse(`${date}T12:00:00Z`);
  if (Number.isNaN(a) || Number.isNaN(b)) return null;
  return Math.round((b - a) / MS_PER_DAY);
}

/** One slot rendered for a human: "Thu 2026-07-30 12:00 (in 3 days)". */
export function formatSlot(slot, from = todayISO()) {
  const n = daysUntil(from, slot.date);
  const when = n === null ? '' : n === 0 ? ' (today)' : n === 1 ? ' (tomorrow)' : ` (in ${n} days)`;
  const label = slot.label ? ` — ${slot.label}` : '';
  return `${slot.dayLabel} ${slot.date} ${slot.time}${when}${label}`;
}
