/**
 * Workers CRUD — register, heartbeat, budget tracking, retire.
 */
import { randomUUID } from 'crypto';
function rowToWorker(r) {
    return {
        id: r.id,
        name: r.name,
        role: r.role,
        client: r.client,
        status: r.status,
        budgetCapUsd: r.budget_cap_usd,
        spentUsd: r.spent_usd,
        score: r.score,
        lastHeartbeat: r.last_heartbeat,
        createdAt: r.created_at,
    };
}
// ─── CRUD ─────────────────────────────────────────────────────────────────────
export function registerWorker(db, input) {
    const id = input.id ?? randomUUID();
    const now = Date.now();
    db.prepare(`
        INSERT INTO workforce_workers (id, name, role, client, status, budget_cap_usd, last_heartbeat, created_at)
        VALUES (?, ?, ?, ?, 'idle', ?, ?, ?)
        ON CONFLICT(id) DO UPDATE SET
          name = excluded.name,
          role = excluded.role,
          client = excluded.client,
          budget_cap_usd = excluded.budget_cap_usd,
          last_heartbeat = excluded.last_heartbeat
    `).run(id, input.name, input.role ?? null, input.client ?? 'unknown', input.budgetCapUsd ?? 10, now, now);
    return getWorker(db, id);
}
export function getWorker(db, id) {
    const row = db.prepare('SELECT * FROM workforce_workers WHERE id = ?').get(id);
    return row ? rowToWorker(row) : null;
}
export function listWorkers(db, status, companyId) {
    if (status && companyId) {
        return db.prepare('SELECT * FROM workforce_workers WHERE status = ? AND company_id = ? ORDER BY created_at').all(status, companyId).map(rowToWorker);
    }
    if (status) {
        return db.prepare('SELECT * FROM workforce_workers WHERE status = ? ORDER BY created_at').all(status).map(rowToWorker);
    }
    if (companyId) {
        return db.prepare('SELECT * FROM workforce_workers WHERE company_id = ? ORDER BY created_at').all(companyId).map(rowToWorker);
    }
    return db.prepare('SELECT * FROM workforce_workers ORDER BY created_at').all().map(rowToWorker);
}
export function listCompanies(db) {
    const rows = db.prepare('SELECT DISTINCT company_id FROM workforce_workers ORDER BY company_id').all();
    return rows.map(r => r.company_id).filter(Boolean);
}
export function heartbeat(db, workerId) {
    db.prepare(`
        UPDATE workforce_workers SET last_heartbeat = ?, status = 'active'
        WHERE id = ? AND status != 'retired'
    `).run(Date.now(), workerId);
}
export function recordSpend(db, workerId, costUsd, tokensUsed) {
    db.prepare(`
        UPDATE workforce_workers SET spent_usd = spent_usd + ?
        WHERE id = ?
    `).run(costUsd, workerId);
    void tokensUsed; // tokens logged on job level
}
export function adjustScore(db, workerId, delta) {
    db.prepare(`
        UPDATE workforce_workers SET score = score + ?
        WHERE id = ?
    `).run(delta, workerId);
}
export function retireWorker(db, workerId) {
    db.prepare(`UPDATE workforce_workers SET status = 'retired' WHERE id = ?`).run(workerId);
}
/** Mark workers silent > staleSecs as stale. Returns IDs updated. */
export function markStaleWorkers(db, staleSecs = 30) {
    const threshold = Date.now() - staleSecs * 1000;
    const rows = db.prepare(`
        SELECT id FROM workforce_workers
        WHERE status = 'active' AND last_heartbeat < ?
    `).all(threshold);
    if (rows.length === 0)
        return [];
    const ids = rows.map((r) => r.id);
    db.prepare(`UPDATE workforce_workers SET status = 'stale' WHERE id IN (${ids.map(() => '?').join(',')})`).run(...ids);
    return ids;
}
