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

export type WorkflowStatus = {
  currentPhase: string | null;
  overallStatus: 'idle' | 'running' | 'blocked' | 'failed' | 'completed';
  lastUpdated: string; // ISO timestamp
  lastFailureReason: string | null;
  nextAction: string;
  completedPhases: string[];
};

const DEFAULT_STATUS_PATH = path.join(process.cwd(), 'status/workflow-status.json');

async function atomicWrite(file: string, data: string) {
  const dir = path.dirname(file);
  await fs.mkdir(dir, { recursive: true });
  const tmp = file + '.tmp';
  await fs.writeFile(tmp, data, 'utf8');
  // If parent directory doesn't exist at rename, just do a normal write
  try {
    await fs.rename(tmp, file);
  } catch (e: any) {
    if (e.code === 'ENOENT') {
      await fs.writeFile(file, data, 'utf8');
      // Clean up temp if it still exists
      try { await fs.unlink(tmp); } catch {}
    } else {
      throw e;
    }
  }
}

export class WorkflowStatusManager {
  private statusPath: string;
  constructor(statusPath = DEFAULT_STATUS_PATH) {
    this.statusPath = statusPath;
  }

  async update(status: WorkflowStatus): Promise<void> {
    await fs.mkdir(path.dirname(this.statusPath), { recursive: true });
    await atomicWrite(this.statusPath, JSON.stringify(status, null, 2));
  }

  async read(): Promise<WorkflowStatus | null> {
    try {
      const txt = await fs.readFile(this.statusPath, 'utf8');
      return JSON.parse(txt) as WorkflowStatus;
    } catch {
      return null;
    }
  }
}
