import { z } from 'zod';

// src/organization-model/ontology.ts
var OntologyKindSchema = z.enum([
  "object",
  "link",
  "action",
  "catalog",
  "event",
  "interface",
  "value-type",
  "property",
  "group",
  "endpoint"
]);
var SYSTEM_PATH_PATTERN = "[a-z0-9][a-z0-9-]*(?:\\.[a-z0-9][a-z0-9-]*)*";
var LOCAL_ID_PATTERN = "[a-z0-9][a-z0-9._-]*";
var ONTOLOGY_ID_PATTERN = `^(global|${SYSTEM_PATH_PATTERN}):(${OntologyKindSchema.options.join("|")})\\/(${LOCAL_ID_PATTERN})$`;
var ONTOLOGY_ID_REGEX = new RegExp(ONTOLOGY_ID_PATTERN);
var OntologyIdSchema = z.string().trim().min(1).max(300).regex(ONTOLOGY_ID_REGEX, "Ontology IDs must use <system-path>:<kind>/<local-id> or global:<kind>/<local-id>");
var OntologyReferenceListSchema = z.array(OntologyIdSchema).default([]).optional();
var OntologyRecordBaseSchema = z.object({
  id: OntologyIdSchema,
  label: z.string().trim().min(1).max(160).optional(),
  description: z.string().trim().min(1).max(2e3).optional(),
  ownerSystemId: z.string().trim().min(1).max(200).optional(),
  aliases: z.array(OntologyIdSchema).optional()
}).passthrough();
var OntologyObjectTypeSchema = OntologyRecordBaseSchema.extend({
  properties: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
  storage: z.record(z.string(), z.unknown()).optional()
});
var OntologyLinkTypeSchema = OntologyRecordBaseSchema.extend({
  from: OntologyIdSchema,
  to: OntologyIdSchema,
  cardinality: z.string().trim().min(1).max(80).optional(),
  via: z.string().trim().min(1).max(255).optional()
});
var OntologyActionTypeSchema = OntologyRecordBaseSchema.extend({
  actsOn: OntologyReferenceListSchema,
  input: z.record(z.string().trim().min(1).max(200), z.unknown()).optional(),
  effects: z.array(z.record(z.string(), z.unknown())).optional()
});
var OntologyCatalogTypeSchema = OntologyRecordBaseSchema.extend({
  kind: z.string().trim().min(1).max(120).optional(),
  appliesTo: OntologyIdSchema.optional(),
  entries: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
});
var OntologyEventTypeSchema = OntologyRecordBaseSchema.extend({
  payload: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
});
var OntologyInterfaceTypeSchema = OntologyRecordBaseSchema.extend({
  properties: z.record(z.string().trim().min(1).max(200), z.unknown()).optional()
});
var OntologyValueTypeSchema = OntologyRecordBaseSchema.extend({
  primitive: z.string().trim().min(1).max(120).optional()
});
var OntologySharedPropertySchema = OntologyRecordBaseSchema.extend({
  valueType: OntologyIdSchema.optional(),
  searchable: z.boolean().optional(),
  pii: z.boolean().optional()
});
var OntologyGroupSchema = OntologyRecordBaseSchema.extend({
  members: OntologyReferenceListSchema
});
var OntologyEndpointTypeSchema = OntologyRecordBaseSchema.extend({
  route: z.string().trim().min(1).max(500).optional()
});
z.object({
  objectTypes: z.record(OntologyIdSchema, OntologyObjectTypeSchema).default({}).optional(),
  linkTypes: z.record(OntologyIdSchema, OntologyLinkTypeSchema).default({}).optional(),
  actionTypes: z.record(OntologyIdSchema, OntologyActionTypeSchema).default({}).optional(),
  catalogTypes: z.record(OntologyIdSchema, OntologyCatalogTypeSchema).default({}).optional(),
  eventTypes: z.record(OntologyIdSchema, OntologyEventTypeSchema).default({}).optional(),
  interfaceTypes: z.record(OntologyIdSchema, OntologyInterfaceTypeSchema).default({}).optional(),
  valueTypes: z.record(OntologyIdSchema, OntologyValueTypeSchema).default({}).optional(),
  sharedProperties: z.record(OntologyIdSchema, OntologySharedPropertySchema).default({}).optional(),
  groups: z.record(OntologyIdSchema, OntologyGroupSchema).default({}).optional(),
  endpoints: z.record(OntologyIdSchema, OntologyEndpointTypeSchema).default({}).optional()
}).default({});
function ontologyGraphNodeId(id) {
  return `ontology:${OntologyIdSchema.parse(id)}`;
}

// src/organization-model/helpers.ts
function childSystemsOf(system) {
  return system.systems ?? system.subsystems ?? {};
}
function getSystem(model, path) {
  const flatMatch = model.systems[path];
  if (flatMatch !== void 0) return flatMatch;
  const segments = path.split(".");
  let current = model.systems;
  let node;
  for (const seg of segments) {
    node = current[seg];
    if (node === void 0) return void 0;
    current = childSystemsOf(node);
  }
  return node;
}

// src/knowledge/queries.ts
var DOMAIN_ITEM_KINDS = ["clients", "roles", "policies", "customers", "offerings", "goals"];
function toGraphNodeId(omNodeId) {
  return `knowledge:${omNodeId}`;
}
function toTargetGraphNodeId(nodeId) {
  if (nodeId.startsWith("system:") || nodeId.startsWith("knowledge:") || nodeId.startsWith("resource:") || nodeId.startsWith("ontology:")) {
    return nodeId;
  }
  const ontologyId = OntologyIdSchema.safeParse(nodeId);
  if (ontologyId.success) {
    return ontologyGraphNodeId(ontologyId.data);
  }
  return `system:${nodeId}`;
}
function buildKnowledgeSourceIdMap(graph) {
  const map = /* @__PURE__ */ new Map();
  for (const node of graph.nodes) {
    if (node.kind === "knowledge" && node.sourceId) {
      map.set(node.id, node.sourceId);
    }
  }
  return map;
}
function bySystem(graph, systemId, knowledgeNodes) {
  const targetGraphNodeId = `system:${systemId}`;
  const governingKnowledgeNodeIds = /* @__PURE__ */ new Set();
  for (const edge of graph.edges) {
    if (edge.kind === "governs" && edge.targetId === targetGraphNodeId && edge.sourceId.startsWith("knowledge:")) {
      governingKnowledgeNodeIds.add(edge.sourceId);
    }
  }
  const sourceIdMap = buildKnowledgeSourceIdMap(graph);
  const matchingOmIds = /* @__PURE__ */ new Set();
  for (const graphNodeId of governingKnowledgeNodeIds) {
    const omId = sourceIdMap.get(graphNodeId);
    if (omId) matchingOmIds.add(omId);
  }
  return knowledgeNodes.filter((n) => matchingOmIds.has(n.id));
}
function byOntology(graph, ontologyId, knowledgeNodes) {
  const targetGraphNodeId = toTargetGraphNodeId(ontologyId);
  const governingKnowledgeNodeIds = /* @__PURE__ */ new Set();
  for (const edge of graph.edges) {
    if (edge.kind === "governs" && edge.targetId === targetGraphNodeId && edge.sourceId.startsWith("knowledge:")) {
      governingKnowledgeNodeIds.add(edge.sourceId);
    }
  }
  const sourceIdMap = buildKnowledgeSourceIdMap(graph);
  const matchingOmIds = /* @__PURE__ */ new Set();
  for (const graphNodeId of governingKnowledgeNodeIds) {
    const omId = sourceIdMap.get(graphNodeId);
    if (omId) matchingOmIds.add(omId);
  }
  return knowledgeNodes.filter((n) => matchingOmIds.has(n.id));
}
function byKind(_graph, kind, knowledgeNodes) {
  return knowledgeNodes.filter((n) => n.kind === kind);
}
function byOwner(_graph, ownerId, knowledgeNodes) {
  return knowledgeNodes.filter((n) => n.ownerIds.includes(ownerId));
}
function governs(graph, nodeId) {
  const graphNodeId = nodeId.startsWith("knowledge:") ? nodeId : toGraphNodeId(nodeId);
  const results = [];
  for (const edge of graph.edges) {
    if (edge.kind === "governs" && edge.sourceId === graphNodeId) {
      results.push(edge.targetId);
    }
  }
  return results;
}
function governedBy(graph, nodeId) {
  const targetId = toTargetGraphNodeId(nodeId);
  const results = [];
  for (const edge of graph.edges) {
    if (edge.kind === "governs" && edge.targetId === targetId) {
      results.push(edge.sourceId);
    }
  }
  return results;
}
function parsePath(pathString) {
  if (!pathString || typeof pathString !== "string") {
    throw new Error("parsePath: path must be a non-empty string");
  }
  if (!pathString.startsWith("/")) {
    throw new Error(`parsePath: path must start with "/", got: "${pathString}"`);
  }
  const normalized = pathString.replace(/\/+$/, "");
  const segments = normalized.split("/").filter((s) => s.length > 0);
  if (segments.length === 0) {
    throw new Error(`parsePath: path resolves to root with no mount: "${pathString}"`);
  }
  const [first, ...rest] = segments;
  if (first === "by-system") {
    if (rest.length === 0) {
      throw new Error(`parsePath: /by-system requires a systemId argument, got: "${pathString}"`);
    }
    return { mount: "by-system", args: [rest.join("/")] };
  }
  if (first === "by-ontology") {
    if (rest.length === 0) {
      throw new Error(`parsePath: /by-ontology requires an ontologyId argument, got: "${pathString}"`);
    }
    return { mount: "by-ontology", args: [rest.join("/")] };
  }
  if (first === "by-kind") {
    if (rest.length === 0) {
      throw new Error(`parsePath: /by-kind requires a kind argument, got: "${pathString}"`);
    }
    return { mount: "by-kind", args: [rest[0]] };
  }
  if (first === "by-owner") {
    if (rest.length === 0) {
      throw new Error(`parsePath: /by-owner requires an ownerId argument, got: "${pathString}"`);
    }
    return { mount: "by-owner", args: [rest.join("/")] };
  }
  if (first === "graph") {
    if (rest.length < 2) {
      throw new Error(`parsePath: /graph requires <nodeId>/<verb> (governs|governed-by), got: "${pathString}"`);
    }
    const graphNodeId = rest.slice(0, -1).join("/");
    const verb = rest[rest.length - 1];
    if (verb !== "governs" && verb !== "governed-by") {
      throw new Error(
        `parsePath: /graph/<nodeId> verb must be "governs" or "governed-by", got: "${verb}" in "${pathString}"`
      );
    }
    return { mount: "graph", args: [graphNodeId, verb] };
  }
  if (first === "all-systems" && rest.length === 0) {
    return { mount: "all-systems", args: [] };
  }
  if (first === "all-resources" && rest.length === 0) {
    return { mount: "all-resources", args: [] };
  }
  if (first === "all-roles" && rest.length === 0) {
    return { mount: "all-roles", args: [] };
  }
  if (first === "by-domain") {
    if (rest.length === 0) {
      throw new Error(`parsePath: /by-domain requires a domain argument, got: "${pathString}"`);
    }
    const domain = rest[0];
    if (!DOMAIN_ITEM_KINDS.includes(domain)) {
      throw new Error(`parsePath: /by-domain unknown domain "${domain}". Supported: ${DOMAIN_ITEM_KINDS.join(", ")}`);
    }
    return { mount: "by-domain", args: [domain] };
  }
  if (first === "by-item") {
    if (rest.length < 2) {
      throw new Error(`parsePath: /by-item requires <domain>/<itemId>, got: "${pathString}"`);
    }
    const domain = rest[0];
    if (!DOMAIN_ITEM_KINDS.includes(domain)) {
      throw new Error(`parsePath: /by-item unknown domain "${domain}". Supported: ${DOMAIN_ITEM_KINDS.join(", ")}`);
    }
    const itemId = rest.slice(1).join("/");
    return { mount: "by-item", args: [domain, itemId] };
  }
  if (segments.length === 1) {
    return { mount: "node", args: [first] };
  }
  throw new Error(
    `parsePath: unrecognized path pattern "${pathString}". Supported: /by-system/<id>, /by-kind/<kind>, /by-owner/<id>, /by-domain/<domain>, /by-item/<domain>/<itemId>, /graph/<nodeId>/governs, /graph/<nodeId>/governed-by, /<nodeId>, /all-systems, /all-resources, /all-roles`
  );
}

// src/knowledge/format.ts
function formatText(results) {
  if (results.length === 0) {
    return "(no results)";
  }
  const kindWidth = Math.max(...results.map((n) => n.kind.length), 8);
  const idWidth = Math.max(...results.map((n) => n.id.length), 4);
  const header = `${"KIND".padEnd(kindWidth)}  ${"ID".padEnd(idWidth)}  TITLE`;
  const divider = "-".repeat(header.length + 20);
  const rows = results.map((n) => {
    const summary = n.summary.length > 80 ? n.summary.slice(0, 77) + "..." : n.summary;
    return `${n.kind.padEnd(kindWidth)}  ${n.id.padEnd(idWidth)}  ${n.title}  \xE2\u20AC\u201D  ${summary}`;
  });
  return [header, divider, ...rows].join("\n");
}
function formatJson(input) {
  const envelope = {
    path: input.path,
    mount: input.parsed.mount,
    args: input.parsed.args,
    results: input.results
  };
  return JSON.stringify(envelope, null, 2);
}
function formatIdsOnly(results) {
  if (results.length === 0) return "";
  const ids = results.map((r) => typeof r === "string" ? r : r.id);
  return ids.join("\n");
}

// src/knowledge/cli-helpers.ts
var OM_SEARCH_HIT_KINDS = ["system", "resource", "knowledge", "ontology", "role", "policy"];
function parseKnowledgeSearchLimit(raw, commandName = "knowledge:search") {
  if (raw === void 0) return 10;
  const n = Number.parseInt(raw, 10);
  if (Number.isNaN(n) || n < 0) {
    throw new Error(`${commandName}: --limit must be a non-negative integer (got "${raw}")`);
  }
  return n;
}
function parseKnowledgeSearchKinds(raw, commandName = "knowledge:search") {
  if (raw === void 0) return void 0;
  const requested = raw.split(",").map((s) => s.trim().toLowerCase()).filter((s) => s.length > 0);
  const valid = [];
  const invalid = [];
  for (const kind of requested) {
    if (OM_SEARCH_HIT_KINDS.includes(kind)) {
      valid.push(kind);
    } else {
      invalid.push(kind);
    }
  }
  if (invalid.length > 0) {
    throw new Error(`${commandName}: unknown kind(s) "${invalid.join(", ")}". Valid: ${OM_SEARCH_HIT_KINDS.join(", ")}`);
  }
  return valid.length > 0 ? valid : void 0;
}
function formatKnowledgeSystemsList(entries) {
  if (entries.length === 0) return "(no results)";
  const pathWidth = Math.max(...entries.map((e) => e.path.length), 4);
  const header = `${"PATH".padEnd(pathWidth)}  LABEL`;
  const divider = "-".repeat(header.length + 20);
  const rows = entries.map((e) => {
    const label = e.system.label ?? e.system.title ?? e.path;
    return `${e.path.padEnd(pathWidth)}  ${label}`;
  });
  return [header, divider, ...rows].join("\n");
}
function formatKnowledgeResourcesList(resources) {
  if (resources.length === 0) return "(no results)";
  const idWidth = Math.max(...resources.map((r) => r.id.length), 4);
  const kindWidth = Math.max(...resources.map((r) => r.kind.length), 4);
  const header = `${"ID".padEnd(idWidth)}  ${"KIND".padEnd(kindWidth)}  TITLE`;
  const divider = "-".repeat(header.length + 20);
  const rows = resources.map((r) => {
    const title = r.title ?? r.id;
    return `${r.id.padEnd(idWidth)}  ${r.kind.padEnd(kindWidth)}  ${title}`;
  });
  return [header, divider, ...rows].join("\n");
}
function formatKnowledgeRolesList(roles) {
  if (roles.length === 0) return "(no results)";
  const idWidth = Math.max(...roles.map((r) => r.id.length), 4);
  const header = `${"ID".padEnd(idWidth)}  TITLE`;
  const divider = "-".repeat(header.length + 20);
  const rows = roles.map((r) => `${r.id.padEnd(idWidth)}  ${r.title}`);
  return [header, divider, ...rows].join("\n");
}
function normalizeKnowledgeNodeId(id) {
  return id.startsWith("knowledge:") ? id.slice("knowledge:".length) : id;
}
function formatKnowledgeInvocationLabel(invocation) {
  switch (invocation.kind) {
    case "slash-command":
      return invocation.command;
    case "mcp-tool":
      return `${invocation.server}/${invocation.name}`;
    case "api-endpoint":
      return `${invocation.method} ${invocation.path}`;
    case "script-execution":
      return invocation.resourceId;
  }
}
function pushActionSource(sources, seen, action) {
  if (!action || action.invocations.length === 0) return;
  const key = `action:${action.id}`;
  if (seen.has(key)) return;
  seen.add(key);
  sources.push({
    kind: "action",
    id: action.id,
    label: action.label,
    targetNodeId: `action:${action.id}`,
    invocations: action.invocations
  });
}
function pushAgentResourceSource(sources, seen, resource) {
  if (!resource || resource.kind !== "agent" || resource.invocations.length === 0) return;
  const agentResource = resource;
  const key = `agent-resource:${agentResource.id}`;
  if (seen.has(key)) return;
  seen.add(key);
  sources.push({
    kind: "agent-resource",
    id: agentResource.id,
    label: agentResource.id,
    targetNodeId: `resource:${agentResource.id}`,
    invocations: agentResource.invocations
  });
}
function resolveKnowledgeInvocationNeighbors(model, id) {
  const normalizedNodeId = normalizeKnowledgeNodeId(id);
  const node = model.knowledge[normalizedNodeId];
  if (!node) return void 0;
  const sources = [];
  const seen = /* @__PURE__ */ new Set();
  for (const link of node.links) {
    const target = link.target;
    if (target.kind === "action") {
      pushActionSource(sources, seen, model.actions[target.id]);
      continue;
    }
    if (target.kind === "resource") {
      pushAgentResourceSource(sources, seen, model.resources[target.id]);
      continue;
    }
    if (target.kind === "system") {
      const system = getSystem(model, target.id);
      for (const actionRef of system?.actions ?? []) {
        pushActionSource(sources, seen, model.actions[actionRef.actionId]);
      }
      for (const resource of Object.values(model.resources)) {
        if (resource.systemPath === target.id) {
          pushAgentResourceSource(sources, seen, resource);
        }
      }
    }
  }
  return {
    id: node.id,
    title: node.title,
    invocationSources: sources.sort((a, b) => a.targetNodeId.localeCompare(b.targetNodeId))
  };
}
function formatKnowledgeInvocationNeighbors(result) {
  const lines = [`Invocation-bearing graph neighbors for ${result.id}`, ""];
  if (result.invocationSources.length === 0) {
    lines.push("  (none)");
  } else {
    for (const source of result.invocationSources) {
      lines.push(`${source.kind}: ${source.id}`);
      for (const invocation of source.invocations) {
        lines.push(`  ${invocation.kind}: ${formatKnowledgeInvocationLabel(invocation)}`);
      }
    }
  }
  return lines.join("\n");
}

export { OM_SEARCH_HIT_KINDS, byKind, byOntology, byOwner, bySystem, formatIdsOnly, formatJson, formatKnowledgeInvocationLabel, formatKnowledgeInvocationNeighbors, formatKnowledgeResourcesList, formatKnowledgeRolesList, formatKnowledgeSystemsList, formatText, governedBy, governs, normalizeKnowledgeNodeId, parseKnowledgeSearchKinds, parseKnowledgeSearchLimit, parsePath, resolveKnowledgeInvocationNeighbors };
