CREATE TABLE IF NOT EXISTS execution_agents (
    id INTEGER PRIMARY KEY,
    agent_key TEXT NOT NULL UNIQUE,
    agent_name TEXT NOT NULL,
    agent_version TEXT NOT NULL,
    environment TEXT NOT NULL,
    host TEXT NOT NULL,
    runtime TEXT NOT NULL,
    capabilities_json TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'unknown' CHECK (status IN ('online','offline','stale','unknown')),
    first_seen_at TEXT NOT NULL,
    last_seen_at TEXT NOT NULL,
    last_heartbeat_at TEXT,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    metadata_json TEXT
);
CREATE INDEX IF NOT EXISTS idx_execution_agents_environment ON execution_agents(environment);
CREATE INDEX IF NOT EXISTS idx_execution_agents_status ON execution_agents(status);
CREATE INDEX IF NOT EXISTS idx_execution_agents_last_seen ON execution_agents(last_seen_at);

ALTER TABLE job_instances ADD COLUMN worker_key TEXT;
ALTER TABLE job_instances ADD COLUMN agent_id INTEGER REFERENCES execution_agents(id) ON DELETE SET NULL;
ALTER TABLE job_instances ADD COLUMN location_type TEXT NOT NULL DEFAULT 'local';
ALTER TABLE job_instances ADD COLUMN location_name TEXT;
CREATE INDEX IF NOT EXISTS idx_job_instances_worker_key ON job_instances(worker_key);
CREATE INDEX IF NOT EXISTS idx_job_instances_agent_id ON job_instances(agent_id);
CREATE INDEX IF NOT EXISTS idx_job_instances_location_type ON job_instances(location_type);
UPDATE job_instances SET worker_key = instance_key WHERE worker_key IS NULL;

CREATE TABLE IF NOT EXISTS remote_events (
    id INTEGER PRIMARY KEY,
    agent_id INTEGER NOT NULL REFERENCES execution_agents(id) ON DELETE CASCADE,
    event_id TEXT NOT NULL,
    worker_key TEXT NOT NULL,
    job_key TEXT NOT NULL,
    event_type TEXT NOT NULL,
    sequence INTEGER,
    occurred_at TEXT NOT NULL,
    received_at TEXT NOT NULL,
    payload_json TEXT NOT NULL,
    processed INTEGER NOT NULL DEFAULT 0 CHECK (processed IN (0, 1)),
    processing_error TEXT,
    UNIQUE(agent_id, event_id)
);
CREATE INDEX IF NOT EXISTS idx_remote_events_worker_at ON remote_events(worker_key, occurred_at);
CREATE INDEX IF NOT EXISTS idx_remote_events_agent_at ON remote_events(agent_id, occurred_at);
CREATE INDEX IF NOT EXISTS idx_remote_events_processed ON remote_events(processed);
