-- metal-kompanion core schema (pgvector)
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS knowledge (
  id          BIGSERIAL PRIMARY KEY,
  source      TEXT,
  path        TEXT,
  sha256      TEXT,
  lineno      INT,
  text        TEXT NOT NULL,
  tags        TEXT[],
  created_at  TIMESTAMPTZ DEFAULT now()
);

-- embeddings: 1024-dim space (extend with more tables if needed)
CREATE TABLE IF NOT EXISTS embeddings_1024 (
  id            BIGSERIAL PRIMARY KEY,
  knowledge_id  BIGINT REFERENCES knowledge(id) ON DELETE CASCADE,
  model         TEXT NOT NULL,
  embedding     vector(1024) NOT NULL,
  created_at    TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS embeddings_1024_l2 ON embeddings_1024 USING ivfflat (embedding vector_l2_ops) WITH (lists=100);

-- memory branches (git-like)
CREATE TABLE IF NOT EXISTS mem_branch (
  id        BIGSERIAL PRIMARY KEY,
  name      TEXT UNIQUE NOT NULL,
  purpose   TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE IF NOT EXISTS mem_commit (
  id         BIGSERIAL PRIMARY KEY,
  branch_id  BIGINT REFERENCES mem_branch(id) ON DELETE CASCADE,
  parent_id  BIGINT,
  author_did TEXT,
  message    TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);
CREATE INDEX IF NOT EXISTS mem_commit_branch ON mem_commit(branch_id);

-- commit deltas referencing knowledge rows
CREATE TABLE IF NOT EXISTS mem_delta (
  id           BIGSERIAL PRIMARY KEY,
  commit_id   BIGINT REFERENCES mem_commit(id) ON DELETE CASCADE,
  knowledge_id BIGINT REFERENCES knowledge(id) ON DELETE CASCADE,
  action      SMALLINT NOT NULL CHECK (action IN (0,1,2)) -- 0:add,1:update,2:delete
);
CREATE INDEX IF NOT EXISTS mem_delta_commit ON mem_delta(commit_id);

-- per-branch centroid for fast routing
CREATE TABLE IF NOT EXISTS branch_embedding_1024 (
  branch_id  BIGINT REFERENCES mem_branch(id) ON DELETE CASCADE,
  model      TEXT NOT NULL,
  embedding  vector(1024) NOT NULL,
  updated_at TIMESTAMPTZ DEFAULT now(),
  PRIMARY KEY(branch_id, model)
);
