// A17 Export — Technisches JSON (execution-prompt §19.1, Wertstrom P7,
// KAR-878/KAR-986). Vollständiger VSM-Datensatz (nodes/connections/layout/
// Szenario-Metadaten) mit Adapter-/Schema-Versionsfeld — pure data assembly,
// no library needed (plain JSON.stringify at the call site).

import type { ScenarioKind, VsmConnection, VsmNode } from '@/lib/vsm-types'

/** Bumped whenever the payload SHAPE below changes (not on every export) —
 * lets an external consumer (Copilot, a future re-import adapter) detect a
 * breaking change instead of guessing from field presence. */
export const WERTSTROM_TECHNICAL_JSON_SCHEMA_VERSION = '1.0.0'
const ADAPTER_ID = 'kadi-v2.wertstrom.technical-export'

export interface WertstromTechnicalJsonInput {
  id: string
  title: string
  description: string | null
  nodes: VsmNode[]
  connections: VsmConnection[]
  layout: Record<string, unknown>
  is_demo: boolean
  scenario_kind: ScenarioKind
  parent_value_stream_id: string | null
  created_at: string
  updated_at: string
  generatedAtLabel: string
}

export interface WertstromTechnicalJsonPayload {
  schemaVersion: string
  adapter: string
  exportedAtLabel: string
  valueStreamMap: {
    id: string
    title: string
    description: string | null
    nodes: VsmNode[]
    connections: VsmConnection[]
    layout: Record<string, unknown>
    is_demo: boolean
    scenario_kind: ScenarioKind
    parent_value_stream_id: string | null
    created_at: string
    updated_at: string
  }
}

/**
 * Full VSM dataset + adapter/schema-version metadata — a plain, versioned
 * passthrough of the already-loaded editor data (nodes/connections/layout),
 * never recomputed or re-derived here (that is Baustein 1/lib/vsm-engine's
 * job; the Copilot-Report is the format that ALSO carries the analysis —
 * this "Technisches JSON" format is the raw dataset only, per §19.1's
 * distinct "Technical JSON" list entry).
 */
export function buildWertstromTechnicalJson(input: WertstromTechnicalJsonInput): WertstromTechnicalJsonPayload {
  return {
    schemaVersion: WERTSTROM_TECHNICAL_JSON_SCHEMA_VERSION,
    adapter: ADAPTER_ID,
    exportedAtLabel: input.generatedAtLabel,
    valueStreamMap: {
      id: input.id,
      title: input.title,
      description: input.description,
      nodes: input.nodes,
      connections: input.connections,
      layout: input.layout,
      is_demo: input.is_demo,
      scenario_kind: input.scenario_kind,
      parent_value_stream_id: input.parent_value_stream_id,
      created_at: input.created_at,
      updated_at: input.updated_at,
    },
  }
}
