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

export type PhaseUpdateEventType = 'phase_started' | 'phase_succeeded' | 'phase_failed' | 'workflow_completed' | 'workflow_blocked';

export type PhaseUpdateEvent = {
  id: string;
  eventType: PhaseUpdateEventType;
  phase: string | null;
  timestamp: string;
  summary: string;
  details?: string | object;
  relayStatus: 'pending' | 'sent';
};

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

function ensureArrayString(details?: string | object): string {
  if (typeof details === 'undefined') return '';
  if (typeof details === 'string') return details;
  try { return JSON.stringify(details); } catch { return String(details); }
}

export async function appendPhaseUpdate(event:
  Omit<PhaseUpdateEvent, 'id' | 'relayStatus' | 'timestamp'> & {
    details?: string | object;
    relayStatus?: 'pending' | 'sent';
    timestamp?: string;
  }
): Promise<PhaseUpdateEvent> {
  const finalized: PhaseUpdateEvent = {
    id: crypto.randomUUID(),
    eventType: event.eventType,
    phase: event.phase ?? null,
    timestamp: event.timestamp || new Date().toISOString(),
    summary: event.summary,
    details: event.details,
    relayStatus: event.relayStatus || 'pending',
  };
  await fs.mkdir(path.dirname(PHASE_UPDATES_QUEUE), { recursive: true });
  await fs.appendFile(PHASE_UPDATES_QUEUE, JSON.stringify(finalized) + '\n', 'utf8');
  return finalized;
}

export async function getPendingPhaseUpdates(): Promise<PhaseUpdateEvent[]> {
  try {
    const data = await fs.readFile(PHASE_UPDATES_QUEUE, 'utf8');
    return data.trim().split(/\r?\n/).filter(Boolean)
      .map(l => JSON.parse(l))
      .filter((e: PhaseUpdateEvent) => e.relayStatus === 'pending');
  } catch {
    return [];
  }
}

export async function markPhaseUpdateSent(id: string): Promise<boolean> {
  try {
    const data = await fs.readFile(PHASE_UPDATES_QUEUE, 'utf8');
    const lines = data.trim().split(/\r?\n/).filter(Boolean);
    let found = false;
    const updatedLines = lines.map(l => {
      const evt = JSON.parse(l) as PhaseUpdateEvent;
      if (evt.id === id && evt.relayStatus === 'pending') {
        found = true;
        evt.relayStatus = 'sent';
      }
      return JSON.stringify(evt);
    });
    if (found) {
      await fs.writeFile(PHASE_UPDATES_QUEUE, updatedLines.join('\n') + '\n', 'utf8');
    }
    return found;
  } catch {
    return false;
  }
}

export async function getAllPhaseUpdates(): Promise<PhaseUpdateEvent[]> {
  try {
    const data = await fs.readFile(PHASE_UPDATES_QUEUE, 'utf8');
    return data.trim().split(/\r?\n/).filter(Boolean).map(l => JSON.parse(l));
  } catch {
    return [];
  }
}
