CREATE TABLE IF NOT EXISTS public.daemon_runtime_registry (
    daemon_id text PRIMARY KEY,
    runtime_kind text NOT NULL,
    host text NOT NULL,
    version text NOT NULL,
    workers_json jsonb NOT NULL DEFAULT '[]'::jsonb,
    metadata_json jsonb NOT NULL DEFAULT '{}'::jsonb,
    started_at timestamptz NOT NULL DEFAULT now(),
    last_seen_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.daemon_runtime_registry
    ADD COLUMN IF NOT EXISTS runtime_kind text NOT NULL DEFAULT 'unknown',
    ADD COLUMN IF NOT EXISTS host text NOT NULL DEFAULT 'unknown-host',
    ADD COLUMN IF NOT EXISTS version text NOT NULL DEFAULT 'unknown',
    ADD COLUMN IF NOT EXISTS workers_json jsonb NOT NULL DEFAULT '[]'::jsonb,
    ADD COLUMN IF NOT EXISTS metadata_json jsonb NOT NULL DEFAULT '{}'::jsonb,
    ADD COLUMN IF NOT EXISTS started_at timestamptz NOT NULL DEFAULT now(),
    ADD COLUMN IF NOT EXISTS last_seen_at timestamptz NOT NULL DEFAULT now();

CREATE INDEX IF NOT EXISTS idx_daemon_runtime_registry_last_seen_at
    ON public.daemon_runtime_registry (last_seen_at DESC);

CREATE INDEX IF NOT EXISTS idx_daemon_runtime_registry_runtime_kind
    ON public.daemon_runtime_registry (runtime_kind);
