import { randomUUID } from 'crypto';
function mapOperative(row) {
    return {
        id: row.id,
        name: row.name,
        roleTitle: row.role_title ?? null,
        reportsToOperativeId: row.reports_to_operative_id ?? null,
        skillId: row.skill_id ?? null,
        specialistId: row.specialist_id ?? null,
        origin: row.origin ?? 'mandate',
        state: row.state,
        suspendReason: row.suspend_reason ?? null,
        terminationReason: row.termination_reason ?? null,
        healthState: row.health_state,
        missionId: row.mission_id ?? null,
        strikeTeamId: row.strike_team_id ?? null,
        budgetCapUsd: Number(row.budget_cap_usd ?? 0),
        budgetScope: row.budget_scope ?? 'operative',
        budgetScopeId: row.budget_scope_id ?? null,
        spentUsd: Number(row.spent_usd ?? 0),
        commendationScore: Number(row.commendation_score ?? 0),
        sortieIntervalMs: Number(row.sortie_interval_ms ?? 30_000),
        lastSortieAt: row.last_sortie_at ?? null,
        createdAt: row.created_at,
    };
}
export function insertOperative(db, input) {
    const id = input.id ?? randomUUID();
    const baseName = (input.name?.trim() || `operative-${id.slice(0, 8)}`).slice(0, 80);
    let name = baseName;
    for (let attempt = 2; getOperativeByName(db, name); attempt++) {
        name = `${baseName}-${attempt}`;
    }
    const budgetScope = input.budgetScope ?? (input.strikeTeamId ? 'crew' : 'operative');
    const budgetScopeId = input.budgetScopeId ?? input.strikeTeamId ?? id;
    db.prepare(`
    INSERT INTO synapse_operatives (
      id, name, role_title, reports_to_operative_id, skill_id, specialist_id, origin, state, suspend_reason, termination_reason, health_state, mission_id,
      strike_team_id, budget_cap_usd, budget_scope, budget_scope_id, spent_usd, commendation_score, sortie_interval_ms,
      last_sortie_at, created_at
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, datetime('now')))
  `).run(id, name, input.roleTitle ?? null, input.reportsToOperativeId ?? null, input.skillId ?? null, input.specialistId ?? null, input.origin ?? 'mandate', input.state ?? 'IDLE', input.suspendReason ?? null, input.terminationReason ?? null, input.healthState ?? 'IDLE', input.missionId ?? null, input.strikeTeamId ?? null, input.budgetCapUsd ?? 10, budgetScope, budgetScopeId, input.spentUsd ?? 0, input.commendationScore ?? 0, input.sortieIntervalMs ?? 30_000, input.lastSortieAt ?? null, input.createdAt ?? null);
    return getOperative(db, id);
}
export function getOperative(db, operativeId) {
    const row = db.prepare('SELECT * FROM synapse_operatives WHERE id=?').get(operativeId);
    return row ? mapOperative(row) : null;
}
export function getOperativeByName(db, name) {
    const row = db.prepare('SELECT * FROM synapse_operatives WHERE name=?').get(name);
    return row ? mapOperative(row) : null;
}
export function getAllOperatives(db) {
    return db.prepare('SELECT * FROM synapse_operatives ORDER BY created_at ASC').all().map(mapOperative);
}
export function getActiveOperatives(db) {
    return db.prepare('SELECT * FROM synapse_operatives WHERE state IN (\'ACTIVE\', \'CHECKOUT\', \'STANDDOWN\')').all().map(mapOperative);
}
export function updateOperativeMission(db, operativeId, missionId, strikeTeamId) {
    db.prepare(`
    UPDATE synapse_operatives
    SET mission_id=?,
        strike_team_id=COALESCE(?, strike_team_id),
        budget_scope=CASE WHEN ? IS NOT NULL THEN 'crew' ELSE budget_scope END,
        budget_scope_id=CASE WHEN ? IS NOT NULL THEN ? ELSE budget_scope_id END
    WHERE id=?
  `).run(missionId, strikeTeamId ?? null, strikeTeamId ?? null, strikeTeamId ?? null, strikeTeamId ?? null, operativeId);
}
export function updateOperativeSpend(db, operativeId, costUsd) {
    db.prepare(`
    UPDATE synapse_operatives
    SET spent_usd=spent_usd + ?, last_sortie_at=datetime('now')
    WHERE id=?
  `).run(costUsd, operativeId);
    return getOperative(db, operativeId);
}
export function updateOperativeHealth(db, operativeId, healthState) {
    db.prepare('UPDATE synapse_operatives SET health_state=? WHERE id=?').run(healthState, operativeId);
}
export function updateOperativeProfile(db, operativeId, patch) {
    db.prepare(`
    UPDATE synapse_operatives
    SET role_title=COALESCE(?, role_title),
        reports_to_operative_id=COALESCE(?, reports_to_operative_id),
        skill_id=COALESCE(?, skill_id),
        specialist_id=COALESCE(?, specialist_id),
        budget_cap_usd=COALESCE(?, budget_cap_usd),
        sortie_interval_ms=COALESCE(?, sortie_interval_ms),
        termination_reason=COALESCE(?, termination_reason)
    WHERE id=?
  `).run(patch.roleTitle ?? null, patch.reportsToOperativeId ?? null, patch.skillId ?? null, patch.specialistId ?? null, patch.budgetCapUsd ?? null, patch.sortieIntervalMs ?? null, patch.terminationReason ?? null, operativeId);
    return getOperative(db, operativeId);
}
export function clearOperativeSuspension(db, operativeId) {
    db.prepare('UPDATE synapse_operatives SET suspend_reason=NULL WHERE id=?').run(operativeId);
}
