import fs from 'fs';
import path from 'path';
/** Delay in ms between 'delivering' and 'done' to allow handoff animation */
export const HANDOFF_DELAY_MS = 2000;
export function createInitialState(config) {
    const { squad } = config;
    const agentCount = squad.agents.length;
    const cols = Math.ceil(Math.sqrt(agentCount));
    const agents = squad.agents.map((agentConfig, index) => {
        const col = (index % cols) + 1;
        const row = Math.floor(index / cols) + 1;
        const stepIdx = squad.pipeline.steps.findIndex(s => s.agent === agentConfig.id);
        const step = stepIdx !== -1 ? squad.pipeline.steps[stepIdx] : null;
        return {
            id: agentConfig.id,
            name: agentConfig.name,
            icon: agentConfig.icon,
            status: 'idle',
            stepIndex: stepIdx + 1,
            stepLabel: step?.label ?? '',
            deliverTo: null,
            desk: { col, row },
            message: null,
        };
    });
    return {
        squad: squad.code,
        status: 'idle',
        step: { current: 0, total: squad.pipeline.steps.length, label: '' },
        agents,
        handoff: null,
        startedAt: null,
        updatedAt: new Date().toISOString(),
    };
}
export function writeState(squadDir, state) {
    const statePath = path.join(squadDir, 'state.json');
    const tmpPath = path.join(squadDir, 'state.json.tmp');
    const data = JSON.stringify(state, null, 2);
    fs.writeFileSync(tmpPath, data, 'utf-8');
    fs.renameSync(tmpPath, statePath);
}
export function readState(squadDir) {
    const statePath = path.join(squadDir, 'state.json');
    if (!fs.existsSync(statePath)) {
        return null;
    }
    const raw = fs.readFileSync(statePath, 'utf-8');
    return JSON.parse(raw);
}
export function updateAgentStatus(state, agentId, status) {
    const agentIndex = state.agents.findIndex(a => a.id === agentId);
    if (agentIndex === -1) {
        throw new Error(`Agent "${agentId}" not found in state`);
    }
    const agents = state.agents.map((a, i) => i === agentIndex ? { ...a, status } : a);
    return {
        ...state,
        agents,
        updatedAt: new Date().toISOString(),
    };
}
export function updateStep(state, current, label) {
    return {
        ...state,
        step: { ...state.step, current, label },
        updatedAt: new Date().toISOString(),
    };
}
export function setHandoff(state, fromId, toId, message) {
    const agents = state.agents.map(a => a.id === fromId ? { ...a, deliverTo: toId } : a);
    return {
        ...state,
        agents,
        handoff: {
            from: fromId,
            to: toId,
            message,
            completedAt: new Date().toISOString(),
        },
        updatedAt: new Date().toISOString(),
    };
}
export function setSquadStatus(state, status) {
    return {
        ...state,
        status,
        updatedAt: new Date().toISOString(),
    };
}
