import { randomUUID } from 'crypto';
function parseArray(value) {
    if (!value)
        return [];
    try {
        return JSON.parse(value);
    }
    catch {
        return [];
    }
}
function getMissionAncestry(db, parentMissionId) {
    if (!parentMissionId)
        return [];
    const row = db.prepare('SELECT ancestry_path FROM synapse_missions WHERE id=?').get(parentMissionId);
    const ancestry = parseArray(row?.ancestry_path);
    return [...ancestry, parentMissionId];
}
function mapMission(row) {
    return {
        id: row.id,
        parentMissionId: row.parent_mission_id ?? null,
        ancestryPath: parseArray(row.ancestry_path),
        correlationId: row.correlation_id ?? null,
        strikeTeamId: row.strike_team_id ?? null,
        title: row.title,
        complexity: row.complexity,
        status: row.status,
        assignedOperativeId: row.assigned_operative_id ?? null,
        requiresApprovalGate: Boolean(row.requires_approval_gate),
        approvalScope: row.approval_scope ?? 'mission',
        approvalScopeId: row.approval_scope_id ?? null,
        budgetScope: row.budget_scope ?? 'mission',
        budgetScopeId: row.budget_scope_id ?? null,
        createdAt: row.created_at,
    };
}
function mapStrikeTeam(row) {
    return {
        id: row.id,
        mandateText: row.mandate_text,
        operativeIds: parseArray(row.operative_ids),
        missionIds: parseArray(row.mission_ids),
        blueprintId: row.blueprint_id ?? null,
        status: row.status,
        createdAt: row.created_at,
    };
}
export function insertMission(db, input) {
    const id = input.id ?? randomUUID();
    const ancestryPath = input.ancestryPath ?? getMissionAncestry(db, input.parentMissionId);
    const correlationId = input.correlationId ?? input.parentMissionId ?? input.strikeTeamId ?? id;
    const approvalScope = input.approvalScope ?? 'mission';
    const approvalScopeId = input.approvalScopeId ?? (approvalScope === 'mission' ? id :
        approvalScope === 'crew' ? input.strikeTeamId ?? id :
            approvalScope === 'operative' ? input.assignedOperativeId ?? id :
                input.strikeTeamId ?? id);
    const budgetScope = input.budgetScope ?? 'mission';
    const budgetScopeId = input.budgetScopeId ?? (budgetScope === 'mission' ? id :
        budgetScope === 'crew' ? input.strikeTeamId ?? id :
            budgetScope === 'operative' ? input.assignedOperativeId ?? id :
                input.strikeTeamId ?? id);
    db.prepare(`
    INSERT INTO synapse_missions (
      id, parent_mission_id, ancestry_path, correlation_id, strike_team_id, title, complexity, status,
      assigned_operative_id, requires_approval_gate, approval_scope, approval_scope_id, budget_scope, budget_scope_id, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')))
  `).run(id, input.parentMissionId ?? null, JSON.stringify(ancestryPath), correlationId, input.strikeTeamId ?? null, input.title, input.complexity ?? 'orchestrate', input.status ?? 'open', input.assignedOperativeId ?? null, input.requiresApprovalGate ? 1 : 0, approvalScope, approvalScopeId, budgetScope, budgetScopeId, input.createdAt ?? null);
    return getMission(db, id);
}
export function getMission(db, missionId) {
    if (!missionId)
        return null;
    const row = db.prepare('SELECT * FROM synapse_missions WHERE id=?').get(missionId);
    return row ? mapMission(row) : null;
}
export function getMissionsForStrikeTeam(db, strikeTeamId) {
    return db.prepare('SELECT * FROM synapse_missions WHERE strike_team_id=? ORDER BY created_at ASC').all(strikeTeamId).map(mapMission);
}
export function updateMissionStatus(db, missionId, status) {
    db.prepare('UPDATE synapse_missions SET status=? WHERE id=?').run(status, missionId);
}
export function insertStrikeTeam(db, input) {
    const id = input.id ?? randomUUID();
    db.prepare(`
    INSERT INTO synapse_strike_teams (
      id, mandate_text, operative_ids, mission_ids, blueprint_id, status, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')))
  `).run(id, input.mandateText, JSON.stringify(input.operativeIds ?? []), JSON.stringify(input.missionIds ?? []), input.blueprintId ?? null, input.status ?? 'deploying', input.createdAt ?? null);
    return getStrikeTeam(db, id);
}
export function getStrikeTeam(db, strikeTeamId) {
    const row = db.prepare('SELECT * FROM synapse_strike_teams WHERE id=?').get(strikeTeamId);
    return row ? mapStrikeTeam(row) : null;
}
export function getAllStrikeTeams(db) {
    return db.prepare('SELECT * FROM synapse_strike_teams ORDER BY created_at DESC').all().map(mapStrikeTeam);
}
export function updateStrikeTeamStatus(db, strikeTeamId, status) {
    db.prepare('UPDATE synapse_strike_teams SET status=? WHERE id=?').run(status, strikeTeamId);
}
export function updateStrikeTeamBlueprint(db, strikeTeamId, blueprintId) {
    db.prepare('UPDATE synapse_strike_teams SET blueprint_id=? WHERE id=?').run(blueprintId, strikeTeamId);
}
