import { promises as fs } from 'fs';
import path from 'path';

export type PhaseProgressLogEntry = {
  phase: string;
  status: 'success' | 'failure';
  attempt: number;
  timestamp: string;
  failureReason?: string;
  nextAction: string;
};

const PHASE_PROGRESS_LOG = path.join(process.cwd(), 'status/phase-progress.jsonl');

export async function logPhaseProgress(entry: PhaseProgressLogEntry, logPath = PHASE_PROGRESS_LOG): Promise<void> {
  await fs.mkdir(path.dirname(logPath), { recursive: true });
  await fs.appendFile(logPath, JSON.stringify(entry) + '\n', 'utf8');
}

export async function getRecentPhaseProgress(limit = 20, logPath = PHASE_PROGRESS_LOG): Promise<PhaseProgressLogEntry[]> {
  try {
    const data = await fs.readFile(logPath, 'utf8');
    const lines = data.trim().split(/\r?\n/).filter(Boolean);
    return lines.slice(-limit).map((line) => JSON.parse(line));
  } catch {
    return [];
  }
}
