import crypto from 'node:crypto';
import path from 'node:path';
import fs from 'node:fs';
import YAML from 'yaml';
export function createPipelineTasks(db, params) {
    const now = new Date().toISOString();
    const tasks = [];
    const insert = db.prepare(`INSERT INTO kanban_tasks
     (id, squad_code, title, description, status, position, step_id, agent_id, agent_name, activity_id, triggered_by, created_at, updated_at)
     VALUES (?, ?, ?, NULL, 'planned', ?, ?, ?, ?, ?, ?, ?, ?)`);
    for (let i = 0; i < params.steps.length; i++) {
        const step = params.steps[i];
        const id = crypto.randomUUID();
        insert.run(id, params.squadCode, step.label, i, step.id, step.agentId, step.agentName, params.activityId, params.triggeredBy, now, now);
        tasks.push({
            id,
            squad_code: params.squadCode,
            title: step.label,
            description: null,
            status: 'planned',
            position: i,
            result: null,
            started_at: null,
            finished_at: null,
            step_id: step.id,
            agent_id: step.agentId,
            agent_name: step.agentName,
            activity_id: params.activityId,
            triggered_by: params.triggeredBy,
            created_at: now,
            updated_at: now,
        });
    }
    return tasks;
}
export function markTaskExecuting(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'executing', started_at = ?, updated_at = ?
     WHERE activity_id = ? AND step_id = ?`).run(now, now, params.activityId, params.stepId);
}
export function markTaskDone(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'done', finished_at = ?, result = ?, updated_at = ?
     WHERE activity_id = ? AND step_id = ?`).run(now, params.result ?? null, now, params.activityId, params.stepId);
}
export function markTaskFailed(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'failed', finished_at = ?, result = ?, updated_at = ?
     WHERE activity_id = ? AND step_id = ?`).run(now, params.error ?? null, now, params.activityId, params.stepId);
}
/**
 * Get the active (running) activity ID for a squad.
 */
export function getActiveActivityId(db, squadCode) {
    const row = db.prepare(`SELECT id FROM squad_activities WHERE squad_code = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1`).get(squadCode);
    return row?.id ?? null;
}
/**
 * Mark a task as executing by its pipeline position (0-based index).
 */
export function markTaskExecutingByPosition(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'executing', started_at = ?, updated_at = ?
     WHERE activity_id = ? AND position = ? AND status = 'planned'`).run(now, now, params.activityId, params.position);
}
/**
 * Mark a task as done by its pipeline position (0-based index).
 */
export function markTaskDoneByPosition(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'done', finished_at = ?, updated_at = ?
     WHERE activity_id = ? AND position = ? AND status = 'executing'`).run(now, now, params.activityId, params.position);
}
export function markAllTasksDone(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'done', finished_at = ?, result = COALESCE(result, ?), updated_at = ?
     WHERE activity_id = ? AND status IN ('planned', 'executing')`).run(now, params.result ?? null, now, params.activityId);
}
export function markAllTasksFailed(db, params) {
    const now = new Date().toISOString();
    db.prepare(`UPDATE kanban_tasks SET status = 'failed', finished_at = ?, result = ?, updated_at = ?
     WHERE activity_id = ? AND status IN ('planned', 'executing')`).run(now, params.error ?? null, now, params.activityId);
}
/**
 * Parse squad.yaml and create pipeline tasks for an activity.
 * Returns empty array if no pipeline steps found or yaml is missing.
 */
export function createPipelineTasksFromYaml(db, squadsDir, squadName, activityId, triggeredBy) {
    try {
        const yamlPath = path.join(squadsDir, squadName, 'squad.yaml');
        if (!fs.existsSync(yamlPath))
            return [];
        const raw = fs.readFileSync(yamlPath, 'utf-8');
        const parsed = YAML.parse(raw);
        const squad = parsed?.squad;
        if (!squad?.pipeline?.steps)
            return [];
        const agents = new Map();
        if (Array.isArray(squad.agents)) {
            for (const a of squad.agents) {
                agents.set(a.id, { id: a.id, name: a.name || a.id });
            }
        }
        const steps = squad.pipeline.steps.map((s) => {
            const agent = s.agent ? agents.get(s.agent) : null;
            return {
                id: s.id,
                label: s.label || s.id,
                agentId: agent?.id ?? null,
                agentName: agent?.name ?? null,
                type: s.type === 'checkpoint' ? 'checkpoint' : 'agent',
            };
        });
        return createPipelineTasks(db, { squadCode: squadName, activityId, triggeredBy, steps });
    }
    catch {
        return [];
    }
}
//# sourceMappingURL=pipeline-task-service.js.map