\set ON_ERROR_STOP on
begin;

create table if not exists public.concept_maps (
  id uuid primary key default gen_random_uuid(),
  key text not null unique,
  title text not null,
  body text not null,
  status text not null default 'active' check (status = any (array['draft'::text, 'active'::text, 'retired'::text])),
  source_ref text,
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  updated_at timestamptz not null default now()
);

create table if not exists public.claim_concept_map_links (
  id uuid primary key default gen_random_uuid(),
  claim_id uuid not null references public.claims(id) on delete cascade,
  concept_map_id uuid not null references public.concept_maps(id) on delete cascade,
  relation text not null check (relation = any (array['derives_from'::text, 'supports'::text, 'contextualizes'::text, 'contains'::text, 'requires'::text, 'relates'::text])),
  weight numeric check (weight >= 0 and weight <= 1),
  rationale text not null,
  source_ref text,
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  unique (claim_id, concept_map_id, relation)
);

create table if not exists public.claim_governance_gate_links (
  id uuid primary key default gen_random_uuid(),
  claim_id uuid not null references public.claims(id) on delete cascade,
  governance_gate_id uuid not null references public.governance_gates(id) on delete cascade,
  relation text not null check (relation = any (array['supports'::text, 'requires'::text, 'constrains'::text, 'documents'::text])),
  weight numeric check (weight >= 0 and weight <= 1),
  rationale text not null,
  source_ref text,
  metadata jsonb not null default '{}'::jsonb,
  created_at timestamptz not null default now(),
  unique (claim_id, governance_gate_id, relation)
);

create index if not exists claim_concept_map_links_claim
  on public.claim_concept_map_links (claim_id, relation);
create index if not exists claim_concept_map_links_map
  on public.claim_concept_map_links (concept_map_id, relation);
create index if not exists claim_governance_gate_links_claim
  on public.claim_governance_gate_links (claim_id, relation);
create index if not exists claim_governance_gate_links_gate
  on public.claim_governance_gate_links (governance_gate_id, relation);

do $$
declare
  inserted_concept_maps int;
  inserted_concept_links int;
  inserted_governance_links int;
begin
  if (
    select count(*) from public.claims where id in (select id from (values
    ('d009dfc4-9755-58a7-affb-80e3e842a775'::uuid),
    ('9bcf7e6b-4e98-52b1-91ef-96cfc15e3df0'::uuid)
  ) as v(id))
  ) <> 2 then
    raise exception 'governance/concept packet requires mapped base claims to exist before inserts';
  end if;

  if (
    select count(*) from public.governance_gates where id in (select id from (values
    ('fa88e31b-6fca-4801-bf72-f5db81950a11'::uuid),
    ('45695897-2a9c-4279-ac25-e59f166dec6a'::uuid)
  ) as v(id))
  ) <> 2 then
    raise exception 'governance/concept packet requires quality/evidence governance gates to exist';
  end if;

  if exists (select 1 from public.concept_maps where id = 'f013126c-0937-5bc8-b021-9697e59057d0'::uuid or key = 'distributed_market_intelligence') then
    raise exception 'governance/concept packet generated concept map already exists';
  end if;

  if exists (select 1 from public.claim_concept_map_links where id = 'af4ce1b9-db03-5bde-a21b-0e16ca0f48b8'::uuid) then
    raise exception 'governance/concept packet generated concept link already exists';
  end if;

  if exists (
    select 1 from public.claim_governance_gate_links
    where id in (select id from (values
    ('1f81e105-af5e-5db8-a7be-08cc6cc4e13a'::uuid),
    ('af04a87e-c1da-57e9-b11c-60d79daa5648'::uuid)
  ) as v(id))
  ) then
    raise exception 'governance/concept packet generated governance link already exists';
  end if;

  insert into public.concept_maps (id, key, title, body, status, source_ref, metadata)
values (
  'f013126c-0937-5bc8-b021-9697e59057d0'::uuid,
  'distributed_market_intelligence',
  'Distributed market intelligence',
  'A concept map for how capital allocation depends on distributed knowledge, incentives, liquidity, feedback loops, and market signals rather than a single central planner.',
  'active',
  'mapped-rich-proposal-14fa5ecc:concept_map:distributed_market_intelligence',
  '{"base_packet_required_first": "production-apply-packet-mapped-20260709", "proposal_id": "14fa5ecc-ac7a-41c1-807d-a2e85b936617", "source_fragment": "capital_allocation_depends_on_distributed_market_intelligence draws_from concept_map:distributed_market_intelligence"}'::jsonb
);
  get diagnostics inserted_concept_maps = row_count;
  if inserted_concept_maps <> 1 then
    raise exception 'governance/concept packet inserted % concept map row(s), expected 1', inserted_concept_maps;
  end if;

  insert into public.claim_concept_map_links
    (id, claim_id, concept_map_id, relation, weight, rationale, source_ref, metadata)
  values
    ('af4ce1b9-db03-5bde-a21b-0e16ca0f48b8'::uuid, 'd009dfc4-9755-58a7-affb-80e3e842a775'::uuid, 'f013126c-0937-5bc8-b021-9697e59057d0'::uuid, 'derives_from', 0.75, 'Mapped proposal 14fa5ecc: the capital-allocation distributed-knowledge claim draws from the distributed market intelligence concept map.', 'mapped-rich-proposal-14fa5ecc:concept_map:distributed_market_intelligence', '{"proposal_id": "14fa5ecc-ac7a-41c1-807d-a2e85b936617"}'::jsonb);
  get diagnostics inserted_concept_links = row_count;
  if inserted_concept_links <> 1 then
    raise exception 'governance/concept packet inserted % concept link row(s), expected 1', inserted_concept_links;
  end if;

  insert into public.claim_governance_gate_links
    (id, claim_id, governance_gate_id, relation, weight, rationale, source_ref, metadata)
  values
    ('1f81e105-af5e-5db8-a7be-08cc6cc4e13a'::uuid, '9bcf7e6b-4e98-52b1-91ef-96cfc15e3df0'::uuid, 'fa88e31b-6fca-4801-bf72-f5db81950a11'::uuid, 'supports', 0.85, 'Specific enough to disagree with requires more than a compressed headline for ambiguous claims.', 'mapped-rich-proposal-ac036c9d:governance_gate:quality-gate', '{"proposal_id": "ac036c9d-20a0-4ffe-881f-57d6b7bacf22"}'::jsonb),
    ('af04a87e-c1da-57e9-b11c-60d79daa5648'::uuid, '9bcf7e6b-4e98-52b1-91ef-96cfc15e3df0'::uuid, '45695897-2a9c-4279-ac25-e59f166dec6a'::uuid, 'supports', 0.85, 'Bodies can state the true evidence tier and scope limits.', 'mapped-rich-proposal-ac036c9d:governance_gate:evidence-bar', '{"proposal_id": "ac036c9d-20a0-4ffe-881f-57d6b7bacf22"}'::jsonb);
  get diagnostics inserted_governance_links = row_count;
  if inserted_governance_links <> 2 then
    raise exception 'governance/concept packet inserted % governance link row(s), expected 2', inserted_governance_links;
  end if;
end $$;

rollback;
