import { v4 as uuidv4 } from 'uuid';

// ---------------------------------------------------------------------------
// Job types
// ---------------------------------------------------------------------------

export type JobStatus = 'queued' | 'running' | 'completed' | 'failed';

export interface ToolCallRecord {
    turn: number;
    tool: string;
    args: unknown;
    timestamp: string;
}

export interface Job {
    id: string;
    agent: string;
    task: string;
    repo?: string;
    status: JobStatus;
    progress: string;
    toolCalls: ToolCallRecord[];
    result?: string;
    error?: string;
    createdAt: string;
    updatedAt: string;
}

// ---------------------------------------------------------------------------
// In-memory store (swap for Redis/DB if scaling horizontally)
// ---------------------------------------------------------------------------

const store = new Map<string, Job>();

export function createJob(agent: string, task: string, repo?: string): Job {
    const job: Job = {
        id: uuidv4(),
        agent,
        task,
        repo,
        status: 'queued',
        progress: 'Job queued',
        toolCalls: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    store.set(job.id, job);
    return job;
}

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

export function updateJob(id: string, updates: Partial<Job>): Job | undefined {
    const job = store.get(id);
    if (!job) return undefined;
    const updated = { ...job, ...updates, id, updatedAt: new Date().toISOString() };
    store.set(id, updated);
    return updated;
}

export function listJobs(limit = 50): Job[] {
    const all = Array.from(store.values());
    return all
        .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
        .slice(0, limit);
}
