import { assessHealth } from './health.js';

function formatDisplayDate(timestamp?: string): string {
  if (!timestamp) return 'n/a';
  const d = new Date(timestamp);
  if (Number.isNaN(d.getTime())) return timestamp;
  return d.toLocaleString('de-DE', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

function main(): void {
  const { status, issues, snapshot } = assessHealth();

  console.log(`STATUS: ${status}`);
  console.log(`HOST_STARTED: ${formatDisplayDate(snapshot.host.process_started_at)}`);
  console.log(
    `MESSAGE_LOOP: ${formatDisplayDate(snapshot.host.message_loop_heartbeat_at)}`,
  );
  console.log(
    `SCHEDULER: ${formatDisplayDate(snapshot.host.scheduler_heartbeat_at)}`,
  );
  console.log(
    `TELEGRAM_CONNECTED: ${formatDisplayDate(snapshot.pipeline.telegram_connected_at)}`,
  );
  console.log(
    `LAST_INBOUND: ${formatDisplayDate(snapshot.pipeline.last_inbound_received_at)}`,
  );
  console.log(
    `LAST_RUN_STARTED: ${formatDisplayDate(snapshot.pipeline.last_run_started_at)}`,
  );
  console.log(
    `LAST_RUN_FINISHED: ${formatDisplayDate(snapshot.pipeline.last_run_finished_at)}`,
  );
  console.log(
    `LAST_REPLY_SENT: ${formatDisplayDate(snapshot.pipeline.last_reply_sent_at)}`,
  );
  console.log(
    `WARDEN_LAST_SUCCESS: ${formatDisplayDate(snapshot.warden.last_success_at)}`,
  );
  console.log(
    `WARDEN_LAST_FAILURE: ${formatDisplayDate(snapshot.warden.last_failure_at)}`,
  );
  console.log(
    `WARDEN_LAST_ERROR: ${snapshot.warden.last_error_code || 'n/a'}${snapshot.warden.last_error_message ? ` (${snapshot.warden.last_error_message})` : ''}`,
  );

  if (issues.length > 0) {
    console.log('ISSUES:');
    for (const issue of issues) {
      console.log(`- ${issue}`);
    }
  }

  if (status === 'error') process.exitCode = 1;
}

main();
