create table if not exists _proxagent_agents (
  id          uuid primary key default gen_random_uuid(),
  slug        text unique not null,
  name        text not null default '',
  system_prompt text not null default '',
  created_at  timestamptz default now()
);

alter table _proxagent_agents enable row level security;

create table if not exists _proxagent_skills (
  id          uuid primary key default gen_random_uuid(),
  agent_id    uuid not null references _proxagent_agents(id) on delete cascade,
  name        text not null,
  description text default '',
  content     text not null,
  is_active   boolean default true,
  updated_at  timestamptz default now(),
  unique(agent_id, name)
);

alter table _proxagent_skills enable row level security;

create table if not exists _proxagent_memories (
  id          uuid primary key default gen_random_uuid(),
  agent_id    uuid not null references _proxagent_agents(id) on delete cascade,
  learning    text not null,
  context     text default '',
  is_active   boolean default true,
  created_at  timestamptz default now()
);

alter table _proxagent_memories enable row level security;

create table if not exists _proxagent_runs (
  id              uuid primary key default gen_random_uuid(),
  agent_id        uuid references _proxagent_agents(id),
  session_id      text unique,
  run_label       text,
  sandbox_id      text,
  model           text,
  subtype         text,
  duration_ms     integer,
  duration_api_ms integer,
  total_cost_usd  numeric,
  input_tokens    integer,
  output_tokens   integer,
  cache_creation_input_tokens integer,
  cache_read_input_tokens     integer,
  num_turns       integer,
  is_error        boolean default false,
  result          text,
  structured_output jsonb,
  started_at      timestamptz default now(),
  ended_at        timestamptz
);

alter table _proxagent_runs enable row level security;

create table if not exists _proxagent_logs (
  id                    uuid primary key default gen_random_uuid(),
  session_id            text not null references _proxagent_runs(session_id),
  sequence              integer not null,
  timestamp             timestamptz default now(),
  message_type          text not null,
  block_type            text,
  tool_name             text,
  tool_input            jsonb,
  text                  text,
  tool_use_id           text,
  tool_result_content   text,
  tool_result_is_error  boolean,
  model                 text,
  error                 text,
  parent_tool_use_id    text,
  subtype               text,
  data                  jsonb,
  thinking              text,
  signature             text,
  uuid                  text,
  user_content          text,
  tool_use_result       jsonb
);

alter table _proxagent_logs enable row level security;

-- Tell PostgREST to pick up the new tables
notify pgrst, 'reload schema';
