import { resolve } from 'path';
import { config } from '../../utils/config.js';
import { createModuleLogger } from '../../utils/logger.js';
import { atomicWriteJSON, readJSON, ensureDir } from '../data-store/file-ops.js';
import type { QueueItem } from '../../types/queue.js';

const log = createModuleLogger('queue-persistence');

export class QueuePersistence {
  private pendingPath: string;
  private failedPath: string;

  constructor(dataDir?: string) {
    const dir = dataDir || config.dataDir;
    this.pendingPath = resolve(dir, 'queue', 'pending.json');
    this.failedPath = resolve(dir, 'queue', 'failed.json');
  }

  async init(): Promise<void> {
    await ensureDir(resolve(this.pendingPath, '..'));
  }

  async savePending(items: QueueItem[]): Promise<void> {
    const pending = items.filter(i => i.status === 'pending' || i.status === 'processing');
    const failed = items.filter(i => i.status === 'failed');
    await atomicWriteJSON(this.pendingPath, pending);
    await atomicWriteJSON(this.failedPath, failed);
    log.debug({ pending: pending.length, failed: failed.length }, 'Queue state persisted');
  }

  async loadPending(): Promise<QueueItem[]> {
    const pending = await readJSON<QueueItem[]>(this.pendingPath) || [];
    // Reset processing items back to pending (they were interrupted)
    for (const item of pending) {
      if (item.status === 'processing') {
        item.status = 'pending';
      }
    }
    log.info({ count: pending.length }, 'Loaded pending queue items');
    return pending;
  }

  async loadFailed(): Promise<QueueItem[]> {
    return await readJSON<QueueItem[]>(this.failedPath) || [];
  }

  async loadAll(): Promise<QueueItem[]> {
    const pending = await this.loadPending();
    const failed = await this.loadFailed();
    return [...pending, ...failed];
  }
}

export const queuePersistence = new QueuePersistence();
