import { v4 as uuid } from 'uuid';
import { buildCurriculum } from '../generator/build.js';
import type { GenerationJob } from '../types.js';

const jobs = new Map<string, GenerationJob>();

export function createJob(triggeredBy: string, reason: 'new_topics' | 'manual'): GenerationJob {
  const job: GenerationJob = {
    id: uuid(),
    triggeredBy,
    reason,
    status: 'queued',
    versionId: null,
    error: null,
    createdAt: new Date(),
    updatedAt: new Date(),
  };
  jobs.set(job.id, job);
  void runPipeline(job.id);
  return job;
}

export function getJob(id: string): GenerationJob | undefined {
  return jobs.get(id);
}

function updateJob(id: string, updates: Partial<Omit<GenerationJob, 'id' | 'createdAt'>>): void {
  const job = jobs.get(id);
  if (!job) return;
  jobs.set(id, { ...job, ...updates, updatedAt: new Date() });
}

async function runPipeline(jobId: string): Promise<void> {
  const job = jobs.get(jobId);
  if (!job) return;

  updateJob(jobId, { status: 'running' });

  try {
    const versionId = await buildCurriculum(job.reason);
    updateJob(jobId, { status: 'done', versionId });
  } catch (err) {
    const error = err instanceof Error ? err.message : String(err);
    updateJob(jobId, { status: 'failed', error });
  }
}
