// Interaction Awareness — SessionStart hook (Layer 2, Node.js)
// Registers session, counts daily sessions, checks late-night usage.

import {
  readStdin, initConfig, requireLayer, getSessionId,
  nowEpoch, nowIso, currentHour, isLateNight,
  STATE_DIR, SESSIONS_LOG, THRESHOLD_SOFT_SESSIONS,
  ensureDir, appendJsonl, writeState, sessionsToday,
  outputWithContext
} from './lib.mjs';

readStdin();
initConfig();
requireLayer(2);

const sid = getSessionId();
if (!sid) {
  process.stdout.write(JSON.stringify({ continue: true }) + '\n');
  process.exit(0);
}

ensureDir(STATE_DIR);

const nowTs = nowEpoch();
const nowIsoStr = nowIso();
const hour = currentHour();
const lateNight = isLateNight();

// Create session state file
const state = {
  start_epoch: nowTs,
  start_iso: nowIsoStr,
  tool_count: 0,
  edit_count: 0,
  last_event_epoch: 0,
  burst_count: 0,
  dep_flags: 0,
  esc_flags: 0,
  fatigue_flags: 0,
  val_flags: 0,
  last_warning_epoch: 0
};
writeState(state);

// Append to sessions.jsonl
appendJsonl(SESSIONS_LOG, {
  session_id: sid,
  start: nowIsoStr,
  hour: hour,
  is_late_night: lateNight
});

// Count today's sessions
const dayCount = sessionsToday();

// Build context message
const hhmm = `${String(hour).padStart(2, '0')}:${String(new Date().getMinutes()).padStart(2, '0')}`;
let msg = 'Interaction Awareness is active. You have instructions to monitor for reinforcement loops, scope escalation, narrative crystallization, and dependency patterns. When you notice these patterns, name them calmly.';
msg += ` Session #${dayCount} today. Started at ${hhmm}.`;

if (lateNight) {
  msg += ` Late-night session (${hhmm}). Sleep deprivation amplifies all interaction risks.`;
}

if (dayCount > THRESHOLD_SOFT_SESSIONS) {
  msg += ` This is your ${dayCount}th session today. Consider whether you need a longer break.`;
}

outputWithContext(msg);
