#!/usr/bin/env bash

# ============================================================================
# ###  ####  ### ###  ### ##### ###  #   #     ###  ##  #    #    ####  ### #####  ##  ###
# #  # #    #     #  #      #   #  #  # #     #    #  # #    #    #    #      #   #  # #  #
# ###  ###  # ##  #   ##    #   ###    #      #    #  # #    #    ###  #      #   #  # ###
# # #  #    #  #  #     #   #   # #    #      #    #  # #    #    #    #      #   #  # # #
# #  # ####  ### ### ###    #   #  #   #       ###  ##  #### #### ####  ###   #    ##  #  #
# ASCII-BANNER
# ============================================================================
# Emits the interface, agent, device and loadout registries as idempotent
# Cypher, read from their declared sources of truth.
# ============================================================================

# ==============================================================================
#   ####   ###  #     #     ##### ##### ####  #### ##### ##### ###  #   # #####
#  #      #   # #     #       #   #     #   # #      #     #      #  #   #   #
#  #      #   # #     #       #   ###   ####  ###    #     ###    #   # #    #
#  #      #   # #     #       #   #     #  #  #      #     #      #    #     #
#   ####   ###  ##### #####   #   ##### #   # ####   #     ##### ###   #     #
#
#        M A I N F R A M E   R E G I S T R Y   C O L L E C T O R
#
# ------------------------------------------------------------------------------
#  Emits the interface, agent, device and loadout registries as idempotent
#  Cypher, read from their declared sources of truth.
#
#  Sources:
#    /root/interfaces/registry.yaml      interfaces, platform endpoints, agents, devices
#    /opt/prodg/registries/loadouts.yaml loadouts
#    /root/.hermes/profiles/             agent runtimes
#
#  Output:
#    /opt/prodg/neo4j/registries.cypher  MERGE-only, safe to re-run
#
#  Rules this script obeys (.github standards):
#    bash standard - shebang, set -euo pipefail, local camelCase, UPPER_SNAKE
#    globals, no function keyword, command substitution over backticks,
#    quoted expansions, indented heredocs with a quoted delimiter.
#    laws.md law 4 - no Python. law 3 - bash and GNU tools first.
# ==============================================================================

set -euo pipefail

readonly INTERFACE_REGISTRY="/root/interfaces/registry.yaml"
readonly LOADOUT_REGISTRY="/opt/prodg/registries/loadouts.yaml"
readonly PRIMITIVE_REGISTRY="/opt/prodg/registries/primitives.yaml"
readonly PLAYBOOK_REGISTRY="/opt/prodg/registries/playbooks.yaml"
readonly ADOPTION_REGISTRY="/opt/prodg/registries/adoption.yaml"
readonly EXTERNAL_DEPS_REGISTRY="/opt/prodg/registries/external-dependencies.yaml"
readonly AGENT_CARDS_REGISTRY="/opt/prodg/registries/agents.yaml"
readonly PROFILE_DIR="/root/.hermes/profiles"
readonly OUT_FILE="/opt/prodg/neo4j/registries.cypher"

interfaceCount=0
agentCount=0
deviceCount=0
loadoutCount=0
primitiveCount=0
playbookCount=0
adoptionCount=0
externalDepCount=0
agentCardCount=0
rewriteCount=0

cypherEscape() {
  local input="$1"
  printf '%s' "${input}" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}

cypherList() {
  local raw="$1"
  local out=""
  local item
  local -a parts
  IFS=, read -ra parts <<< "${raw}"
  for item in "${parts[@]}"; do
    [ -z "${item}" ] && continue
    [ -n "${out}" ] && out="${out}, "
    out="${out}\"$(cypherEscape "${item}")\""
  done
  printf '[%s]' "${out}"
}

emit() {
  printf '%s\n' "$1" >> "${OUT_FILE}"
}

emitEntry() {
  local registry="$1" key="$2" label="$3" props="$4"
  emit "MERGE (e:Entry:${label} {registry: \"${registry}\", key: \"$(cypherEscape "${key}")\"})"
  emit "SET ${props}, e.source = \"declared\", e.updated = datetime();"
  # Bind BOTH endpoints, then merge the edge. A full-pattern MERGE of
  # (e)-[:IN_REGISTRY]->(:Registry {key: ...}) tries to create a new Registry
  # node and violates the uniqueness constraint, because an anonymous node in a
  # MERGE pattern is created rather than matched.
  emit "MATCH (e:Entry:${label} {registry: \"${registry}\", key: \"$(cypherEscape "${key}")\"})"
  emit "MATCH (r:Registry {key: \"${registry}\"})"
  emit "MERGE (e)-[:IN_REGISTRY]->(r);"
}

requireFile() {
  local path="$1"
  if [ ! -f "${path}" ]; then
    printf 'collector: required source missing: %s\n' "${path}" >&2
    exit 1
  fi
}

command -v yq >/dev/null 2>&1 || { printf 'collector: yq is required\n' >&2; exit 1; }
: > "${OUT_FILE}"

emit "// GENERATED by neo4j/collect-registries.sh - do not edit by hand."
emit "// Idempotent: MERGE-only, safe to re-run."
emit ""

# ------------------------------------------------------------------ interfaces
if [ -f "${INTERFACE_REGISTRY}" ]; then
  # Every interface carries a track. Entries with no track declared default to
  # adopt_and_run; a study_and_rewrite interface is a queued rewrite target and
  # must carry spec_to_mine, which is what the doctor checks.
  while IFS=$'\t' read -r id name url category track spec; do
    [ -z "${id}" ] && continue
    emitEntry "interface" "${id}" "Interface" \
      "e.name = \"$(cypherEscape "${name}")\", e.url = \"$(cypherEscape "${url}")\", e.category = \"$(cypherEscape "${category}")\", e.exposure = \"gateway\", e.track = \"$(cypherEscape "${track}")\", e.specToMine = \"$(cypherEscape "${spec}")\""
    interfaceCount=$((interfaceCount + 1))
  done < <(yq -r '.interfaces[]? | [.id, .name, .url, .category, (.track // "adopt_and_run"), (.spec_to_mine // "")] | @tsv' "${INTERFACE_REGISTRY}")

  while IFS=$'\t' read -r key url; do
    [ -z "${key}" ] && continue
    emitEntry "interface" "${key}" "Interface" \
      "e.name = \"$(cypherEscape "${key}")\", e.url = \"$(cypherEscape "${url}")\", e.category = \"platform\", e.exposure = \"client\", e.track = \"adopt_and_run\", e.specToMine = \"\""
    interfaceCount=$((interfaceCount + 1))
  done < <(yq -r '.platform_interfaces // {} | to_entries[] | [.key, (.value.desktop_url // .value.bot_username // .value.deep_link_scheme // "n/a")] | @tsv' "${INTERFACE_REGISTRY}")

  while IFS=$'\t' read -r id name kind os capabilities; do
    [ -z "${id}" ] && continue
    emitEntry "device" "${id}" "Device" \
      "e.name = \"$(cypherEscape "${name}")\", e.device_type = \"$(cypherEscape "${kind}")\", e.platform = \"$(cypherEscape "${os}")\", e.capabilities = $(cypherList "${capabilities}")"
    deviceCount=$((deviceCount + 1))
  done < <(yq -r '.devices[]? | [.id, .name, .device_type, (.os // "unknown"), ((.capabilities // []) | join(","))] | @tsv' "${INTERFACE_REGISTRY}")

  while IFS=$'\t' read -r id name role status interfaces skills; do
    [ -z "${id}" ] && continue
    emitEntry "agent" "${id}" "Agent" \
      "e.name = \"$(cypherEscape "${name}")\", e.role = \"$(cypherEscape "${role}")\", e.status = \"$(cypherEscape "${status}")\", e.skills = $(cypherList "${skills}"), e.runtime = \"declared\""
    agentCount=$((agentCount + 1))
    IFS=, read -ra ifaceList <<< "${interfaces}"
    for ifaceId in "${ifaceList[@]}"; do
      [ -z "${ifaceId}" ] && continue
      emit "MATCH (a:Entry:Agent {registry: \"agent\", key: \"$(cypherEscape "${id}")\"}), (i:Entry:Interface {registry: \"interface\", key: \"$(cypherEscape "${ifaceId}")\"}) MERGE (a)-[:EXPOSED_VIA]->(i);"
    done
  done < <(yq -r '.sdlc_agents[]? | [.id, .name, .role, .status, ((.interfaces // []) | join(",")), ((.skills // []) | join(","))] | @tsv' "${INTERFACE_REGISTRY}")
fi

# ------------------------------------------------------------ agent runtimes
if [ -d "${PROFILE_DIR}" ]; then
  for profilePath in "${PROFILE_DIR}"/*/; do
    [ -d "${profilePath}" ] || continue
    profileName="$(basename "${profilePath}")"
    emitEntry "agent" "profile-${profileName}" "Agent" \
      "e.name = \"$(cypherEscape "${profileName}")\", e.role = \"hermes runtime profile\", e.status = \"running\", e.runtime = \"hermes-profile\""
    agentCount=$((agentCount + 1))
  done
fi

# ---------------------------------------------------------------- loadouts
if [ -f "${LOADOUT_REGISTRY}" ]; then
  while IFS=$'\t' read -r key name mandatory summary edition tenancy hardware; do
    [ -z "${key}" ] && continue
    emitEntry "loadout" "${key}" "Loadout" \
      "e.name = \"$(cypherEscape "${name}")\", e.mandatory = ${mandatory}, e.summary = \"$(cypherEscape "${summary}")\", e.version = \"0.1.0\", e.edition = ${edition}, e.tenancy = \"$(cypherEscape "${tenancy}")\", e.hardware = \"$(cypherEscape "${hardware}")\""
    loadoutCount=$((loadoutCount + 1))
  done < <(yq -r '.loadouts[]? | [.key, .name, (.mandatory | tostring), .summary, ((.edition // false) | tostring), (.tenancy // "none"), (.hardware // "unspecified")] | @tsv' "${LOADOUT_REGISTRY}")

  while IFS=$'\t' read -r key requires; do
    [ -z "${key}" ] && continue
    IFS=, read -ra reqList <<< "${requires}"
    for req in "${reqList[@]}"; do
      [ -z "${req}" ] && continue
      emit "MATCH (l:Entry:Loadout {registry: \"loadout\", key: \"$(cypherEscape "${key}")\"}), (r:Entry:Loadout {registry: \"loadout\", key: \"$(cypherEscape "${req}")\"}) MERGE (l)-[:REQUIRES]->(r);"
    done
  done < <(yq -r '.loadouts[]? | [.key, ((.requires // []) | join(","))] | @tsv' "${LOADOUT_REGISTRY}")

  while IFS=$'\t' read -r key services; do
    [ -z "${key}" ] && continue
    IFS=, read -ra svcList <<< "${services}"
    for svc in "${svcList[@]}"; do
      [ -z "${svc}" ] && continue
      emit "MATCH (l:Entry:Loadout {registry: \"loadout\", key: \"$(cypherEscape "${key}")\"}), (s:Entry:Service {registry: \"service\", key: \"$(cypherEscape "${svc}")\"}) MERGE (l)-[:CONTAINS]->(s);"
    done
  done < <(yq -r '.loadouts[]? | [.key, ((.services // []) | join(","))] | @tsv' "${LOADOUT_REGISTRY}")
fi

# ------------------------------------------------------------------ primitives
if [ -f "${PRIMITIVE_REGISTRY}" ]; then
  while IFS=$'\t' read -r key name intent risk approval reversible evidence; do
    [ -z "${key}" ] && continue
    emitEntry "primitive" "${key}" "Primitive" \
      "e.name = \"$(cypherEscape "${name}")\", e.intent = \"$(cypherEscape "${intent}")\", e.risk = \"$(cypherEscape "${risk}")\", e.approval = \"$(cypherEscape "${approval}")\", e.reversible = ${reversible}, e.evidence = \"$(cypherEscape "${evidence}")\""
    primitiveCount=$((primitiveCount + 1))
  done < <(yq -r '.primitives[]? | [.key, .name, .intent, .risk, .approval, (.reversible | tostring), .evidence] | @tsv' "${PRIMITIVE_REGISTRY}")
fi

# ------------------------------------------------------------------- playbooks
# A playbook is data: steps bind primitives to a phase. The edge carries the
# phase, so the same primitive used twice in different phases stays distinct.
if [ -f "${PLAYBOOK_REGISTRY}" ]; then
  while IFS=$'\t' read -r key name class summary; do
    [ -z "${key}" ] && continue
    emitEntry "playbook" "${key}" "Playbook" \
      "e.name = \"$(cypherEscape "${name}")\", e.class = \"$(cypherEscape "${class}")\", e.summary = \"$(cypherEscape "${summary}")\""
    playbookCount=$((playbookCount + 1))
  done < <(yq -r '.playbooks[]? | [.key, .name, .class, (.summary | gsub("\n"; " ") | .[0:200])] | @tsv' "${PLAYBOOK_REGISTRY}")

  while IFS=$'\t' read -r pbKey phase primitiveKey; do
    [ -z "${pbKey}" ] && continue
    [ -z "${primitiveKey}" ] && continue
    emit "MATCH (p:Entry:Playbook {registry: \"playbook\", key: \"$(cypherEscape "${pbKey}")\"}), (v:Entry:Primitive {registry: \"primitive\", key: \"$(cypherEscape "${primitiveKey}")\"}) MERGE (p)-[:USES {phase: \"$(cypherEscape "${phase}")\"}]->(v);"
  done < <(yq -r '.playbooks[]? | .key as $p | .steps[]? | [$p, .phase, .primitive] | @tsv' "${PLAYBOOK_REGISTRY}")
fi

# ------------------------------------------------------------------- adoption
# The build-vs-borrow record. An unrecorded dependency is an unreviewed
# dependency, so a component with no licence is a finding rather than a gap.
#
# Every entry also carries a track. adopt_and_run is the default; an entry on the
# study_and_rewrite track is a queued clean-room reimplementation target and
# carries spec_to_mine (what to reimplement from) and clean_room (the boundary
# that keeps the rewrite free of the upstream licence).
if [ -f "${ADOPTION_REGISTRY}" ]; then
  adoptionKeys=""
  while IFS=$'\t' read -r key name verdict licence language rationaleLength track spec cleanRoom; do
    [ -z "${key}" ] && continue
    emitEntry "adoption" "${key}" "Adoption" \
      "e.name = \"$(cypherEscape "${name}")\", e.verdict = \"$(cypherEscape "${verdict}")\", e.licence = \"$(cypherEscape "${licence}")\", e.language = \"$(cypherEscape "${language}")\", e.rationaleLength = \"${rationaleLength}\", e.track = \"$(cypherEscape "${track}")\", e.specToMine = \"$(cypherEscape "${spec}")\", e.cleanRoom = \"$(cypherEscape "${cleanRoom}")\""
    adoptionCount=$((adoptionCount + 1))
    if [ "${track}" = "study_and_rewrite" ]; then
      rewriteCount=$((rewriteCount + 1))
    fi
    adoptionKeys="${adoptionKeys:+${adoptionKeys}, }\"$(cypherEscape "${key}")\""
  done < <(yq -r '.entries[]? | [.key, .name, .verdict, .licence, (.language // "unknown"), ((.rationale // "") | length | tostring), (.track // "adopt_and_run"), (.spec_to_mine // ""), (.clean_room // "")] | @tsv' "${ADOPTION_REGISTRY}")

  # Reconcile, do not only merge. A decision removed from the YAML must leave
  # the graph: MERGE alone only ever adds, so superseded decisions linger as
  # phantom nodes and produce phantom findings. That is precisely the drift the
  # registry exists to prevent, and it caught a stale entry on first run.
  if [ -n "${adoptionKeys}" ]; then
    emit "MATCH (a:Entry:Adoption) WHERE NOT a.key IN [${adoptionKeys}] DETACH DELETE a;"
  fi
fi

# ---------------------------------------------- external dependencies (SSA-2)
# The declared egress surface required by self-sovereign architecture. An
# undeclared dependency is worse than a documented one, so an entry with no exit
# path is a finding rather than a gap.
if [ -f "${EXTERNAL_DEPS_REGISTRY}" ]; then
  while IFS=$'\t' read -r key name kind endpoint status; do
    [ -z "${key}" ] && continue
    emitEntry "external-dependency" "${key}" "ExternalDependency" \
      "e.name = \"$(cypherEscape "${name}")\", e.kind = \"$(cypherEscape "${kind}")\", e.endpoint = \"$(cypherEscape "${endpoint}")\", e.status = \"$(cypherEscape "${status}")\""
    externalDepCount=$((externalDepCount + 1))
  done < <(yq -r '.dependencies[]? | [.key, .name, .kind, (.endpoint // "unknown"), (.status // "open")] | @tsv' "${EXTERNAL_DEPS_REGISTRY}")
fi

# ------------------------------------------- agent cards (HELM handshake)
# The card ENRICHES the agent entry rather than creating a second one: same
# registry and key, so MERGE adds the tier and the declared scope to the agent
# the other collectors already found. An agent whose scope is undeclared is the
# finding - the Mainframe's agents are currently known by what they overwrote,
# not by a stated contract.
if [ -f "${AGENT_CARDS_REGISTRY}" ]; then
  while IFS=$'\t' read -r key name tier declaredScope runtime role; do
    [ -z "${key}" ] && continue
    emit "MERGE (e:Entry:Agent {registry: \"agent\", key: \"$(cypherEscape "${key}")\"})"
    emit "SET e.cardName = \"$(cypherEscape "${name}")\", e.tier = \"$(cypherEscape "${tier}")\", e.declaredScope = \"$(cypherEscape "${declaredScope}")\", e.cardUpdated = datetime(), e.source = coalesce(e.source, \"declared\"), e.runtime = coalesce(e.runtime, \"$(cypherEscape "${runtime}")\"), e.name = coalesce(e.name, \"$(cypherEscape "${name}")\"), e.role = coalesce(e.role, \"$(cypherEscape "${role}")\");"
    emit "MATCH (e:Entry:Agent {registry: \"agent\", key: \"$(cypherEscape "${key}")\"})"
    emit "MATCH (r:Registry {key: \"agent\"})"
    emit "MERGE (e)-[:IN_REGISTRY]->(r);"
    agentCardCount=$((agentCardCount + 1))
  done < <(yq -r '.cards[]? | [.key, .name, (.tier // "undeclared"), (.declared_scope // "undeclared"), (.runtime // "declared"), (.role // "undeclared")] | @tsv' "${AGENT_CARDS_REGISTRY}")
fi

printf 'collector: %d interfaces, %d agents, %d devices, %d loadouts, %d primitives, %d playbooks, %d adoption, %d external-deps, %d agent-cards -> %s\n' \
  "${interfaceCount}" "${agentCount}" "${deviceCount}" "${loadoutCount}" "${primitiveCount}" "${playbookCount}" "${adoptionCount}" "${externalDepCount}" "${agentCardCount}" "${OUT_FILE}"
