-- Daemon capabilities for multi-daemon work distribution
-- Adds selection scoring and task assignment tracking

-- Extend daemons table for multi-daemon selection
ALTER TABLE daemons ADD COLUMN IF NOT EXISTS capacity_score INTEGER DEFAULT 100;
ALTER TABLE daemons ADD COLUMN IF NOT EXISTS task_queue_length INTEGER DEFAULT 0;
ALTER TABLE daemons ADD COLUMN IF NOT EXISTS supports_migration BOOLEAN DEFAULT true;

-- Track active task assignments per daemon
-- This allows moving tasks between daemons
CREATE TABLE IF NOT EXISTS daemon_task_assignments (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    daemon_id UUID NOT NULL REFERENCES daemons(id) ON DELETE CASCADE,
    task_id UUID NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
    assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    status VARCHAR(32) NOT NULL DEFAULT 'active',  -- active, migrating, completed

    UNIQUE(task_id)  -- A task can only be assigned to one daemon at a time
);

CREATE INDEX idx_daemon_task_assignments_daemon_id ON daemon_task_assignments(daemon_id);
CREATE INDEX idx_daemon_task_assignments_status ON daemon_task_assignments(status);

COMMENT ON COLUMN daemons.capacity_score IS 'Relative capacity score for daemon selection (higher = more capacity)';
COMMENT ON COLUMN daemons.task_queue_length IS 'Number of tasks queued/waiting on this daemon';
COMMENT ON COLUMN daemons.supports_migration IS 'Whether this daemon supports task migration';
COMMENT ON TABLE daemon_task_assignments IS 'Tracks task-to-daemon assignments for migration support';
