import { existsSync, readFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { LOG_FILE } from './daemon.js';

interface LogsOpts {
  follow?: boolean;
  lines?: number;
}

export function runLogs(opts: LogsOpts): void {
  if (!existsSync(LOG_FILE)) {
    console.log('No log file found. Is the gateway installed?');
    return;
  }

  if (opts.follow) {
    const lines = opts.lines ?? 50;
    const tail = spawn('tail', ['-n', lines.toString(), '-f', LOG_FILE], {
      stdio: 'inherit',
    });
    tail.on('error', () => {
      // Fallback for systems without tail
      console.log(readLastLines(opts.lines ?? 50));
      console.log('\n(--follow requires `tail` command)');
    });
    return;
  }

  // Just print last N lines
  console.log(readLastLines(opts.lines ?? 50));
}

function readLastLines(n: number): string {
  const content = readFileSync(LOG_FILE, 'utf-8');
  const lines = content.split('\n');
  return lines.slice(-n).join('\n');
}
