/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const BT = '`';
const FENCE = BT.repeat(3);
export function diagramExportSkillMd() {
    return [
        '---',
        'name: diagram-export',
        'description: >-',
        '  Design, validate, and export Mermaid diagrams following Salesforce Architect standards.',
        '  Supports Lucidchart (via MCP OAuth), draw.io, and local SVG/PDF rendering.',
        '  Validates Mermaid syntax before every export. USE FOR: export diagram, push to lucid,',
        '  lucidchart diagram, drawio export, draw.io, visio, diagram export, diagram sync,',
        '  render diagram, mermaid to pdf, mermaid to svg, salesforce architecture diagram,',
        '  solution diagram, system landscape, capability map, data model, roadmap diagram,',
        '  salesforce architect standard, lucid ai prompt. Reusable by BA, PM, and Architect profiles.',
        '---',
        '',
        '# Diagram Export',
        '',
        '## Prerequisites',
        '',
        '| Tool | Check | Install |',
        '|------|-------|---------|',
        '| Node.js >= 18 | ' + BT + 'node --version' + BT + ' | [https://nodejs.org](https://nodejs.org) |',
        '| npx | ' + BT + 'npx --version' + BT + ' | Included with Node.js |',
        '| mermaid-to-drawio (optional) | ' +
            BT +
            'command -v mermaid-to-drawio' +
            BT +
            ' | ' +
            BT +
            'npm install -g mermaid-to-drawio' +
            BT +
            ' |',
        '| Lucid MCP (for lucid target) | Configured via Setup Agents UI OAuth flow | See Lucidchart section below |',
        '',
        '> mermaid-cli is auto-downloaded via ' +
            BT +
            'npx -y @mermaid-js/mermaid-cli' +
            BT +
            '. No manual install needed.',
        '',
        '---',
        '',
        '## CRITICAL: Mermaid Syntax Validation',
        '',
        '**Always validate Mermaid syntax before exporting or embedding in any document.**',
        'The validator is the rendering engine itself — run it explicitly:',
        '',
        FENCE + 'bash',
        '# Lint a .mmd file — exit 0 = valid, exit non-zero = syntax error',
        'npx -y @mermaid-js/mermaid-cli -i diagram.mmd -o /tmp/lint-check.svg',
        'echo "Exit code: $?"',
        FENCE,
        '',
        '**Guardrails (MANDATORY):**',
        '',
        '1. **Before exporting:** always run the validator above. Never skip.',
        '2. **After AI generation:** treat every generated diagram as untrusted until validated.',
        '3. **When embedding in Markdown:** validate the fenced block contents, not just the text.',
        '4. **On parse error:** read the error message carefully — it includes the exact line and',
        '   character. Fix that specific location, then re-validate. Do NOT guess-fix blindly.',
        '5. **Never suppress errors** with fallback to a simpler diagram without telling the user.',
        '',
        '---',
        '',
        '## Diagram Fidelity Classification (CRITICAL)',
        '',
        'Classify every diagram task before drawing:',
        '',
        '| Class | Meaning | Authoritative target |',
        '|-------|---------|----------------------|',
        '| `semantic` | Explain the idea, relationships, or architecture for review | Mermaid is usually enough |',
        '| `inspired-by-reference` | Borrow structure or style from a source, without exact fidelity | Mermaid, draw.io, or Lucid |',
        '| `recreation` | Reproduce a source PDF, image, Lucid, draw.io, or screenshot | draw.io XML / Lucid / measured SVG |',
        '',
        '**Rules:**',
        '- For `recreation`, acceptance is pixel-perfect source fidelity unless the user explicitly accepts an approximation.',
        '- Structural similarity is not enough for a recreation.',
        '- Mermaid is a semantic diagram target; do not present Mermaid as a pixel-perfect recreation when exact layout, connector anchors, icons, rotations, or styling matter.',
        '- Escalate to draw.io XML or Lucid when exact geometry, connector bend points, line jumps, or manual label placement are acceptance criteria.',
        '- For source-free diagrams, define a diagram contract before drawing: purpose, audience, nodes, groups, relationships, labels, reading flow, and expected connector endpoints.',
        '',
        '### Post-Render Visual QA',
        '',
        'After rendering, inspect the actual SVG/PDF/PNG output before handoff:',
        '',
        '- Text fits inside every container.',
        '- Containers are sized and balanced after real labels are placed.',
        '- Connector endpoints visibly leave the intended source edge and land on the intended target edge.',
        '- Arrowheads are visible and not hidden behind shapes.',
        '- Lines do not cross labels, important symbols, or containers unless the source explicitly requires it.',
        '- Labels have clearance from borders, connectors, and arrowheads.',
        '- Whitespace is intentional and does not make the layout look broken.',
        '- Editable source and rendered output are equivalent; do not make SVG-only fixes that cannot be regenerated.',
        '',
        'Record residual fidelity gaps when the output is an approximation.',
        '',
        '### Common Mermaid Errors and Fixes',
        '',
        '| Error Pattern | Cause | Fix |',
        '|--------------|-------|-----|',
        '| `Parse error on line N` | Syntax mistake at that line | Read the `^` pointer, fix that token |',
        '| `No diagram detected` | Missing or wrong diagram type declaration | Add ' +
            BT +
            'graph TD' +
            BT +
            ' / ' +
            BT +
            'sequenceDiagram' +
            BT +
            ' on line 1 |',
        '| `UnknownDiagramError` | Unsupported diagram type | Check supported types at [mermaid.js.org/intro](https://mermaid.js.org/intro/) |',
        '| `Duplicate node id` | Same node id defined twice | Rename one node |',
        '| Edge label without content | ' + BT + 'A -->|  | B' + BT + ' | Fill the label or remove pipes |',
        '',
        '---',
        '',
        '## Salesforce Architect Diagram Standards',
        '',
        'Before generating any architecture diagram, consult the official Salesforce Architect',
        'reference to choose the correct diagram type for the domain and audience.',
        '',
        '### Reference Documentation (READ BEFORE DESIGNING)',
        '',
        '| Resource | Purpose |',
        '|----------|---------|',
        '| [Diagram Gallery](https://architect.salesforce.com/diagrams) | Browse real-world Salesforce architecture diagram examples |',
        '| [Introduction](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/introduction) | When to use each diagram type |',
        '| [Kit of Parts](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/kit-of-parts.html) | Official shape vocabulary and notation |',
        '| [Data Model Notation](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/data-model-notation.html) | ERD conventions for Salesforce objects |',
        '| [Capability Map](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/section-capability-map.html) | Business capabilities by domain |',
        '| [Solution Architecture](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/section-solution-architecture.html) | Integration, component, and deployment views |',
        '| [System Landscape](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/section-system-landscape.html) | Cross-system context and boundaries |',
        '| [Roadmap](https://architect.salesforce.com/docs/architect/reference-diagrams/guide/section-roadmap.html) | Phased delivery and release planning |',
        '',
        '### Diagram Type Decision Matrix',
        '',
        '| User Request | Standard Diagram Type | Mermaid Type |',
        '|-------------|----------------------|--------------|',
        '| "Show how systems connect" | System Landscape | ' + BT + 'graph LR' + BT + ' |',
        '| "Show the data model / objects" | Data Model | ' + BT + 'erDiagram' + BT + ' |',
        '| "Show what the system does" | Capability Map | ' + BT + 'mindmap' + BT + ' or ' + BT + 'graph TD' + BT + ' |',
        '| "Show how components integrate" | Solution Architecture | ' + BT + 'graph LR' + BT + ' with swimlanes |',
        '| "Show the delivery plan / phases" | Roadmap | ' + BT + 'gantt' + BT + ' or ' + BT + 'timeline' + BT + ' |',
        '| "Show a process / user flow" | Sequence / Flow | ' +
            BT +
            'sequenceDiagram' +
            BT +
            ' or ' +
            BT +
            'flowchart TD' +
            BT +
            ' |',
        '| "Show states / lifecycle" | State Machine | ' + BT + 'stateDiagram-v2' + BT + ' |',
        '',
        '**Agent rule:** Always ask "What is the audience and purpose?" before picking a diagram type.',
        'A developer needs a sequence diagram; a CIO needs a system landscape. Same domain, different diagram.',
        '',
        '### Salesforce Kit of Parts — Shape Mapping to Mermaid',
        '',
        'The official Kit of Parts uses specific shapes. Map them to Mermaid nodes:',
        '',
        '| Salesforce Shape | Mermaid Syntax | Use for |',
        '|-----------------|----------------|---------|',
        '| Cloud (Salesforce org) | ' + BT + 'A[(Org Name)]' + BT + ' | Salesforce orgs, Experience Cloud |',
        '| Rectangle (System) | ' + BT + 'A[System Name]' + BT + ' | External systems, apps |',
        '| Rounded rect (Process) | ' + BT + 'A(Process Name)' + BT + ' | Flows, processes, actions |',
        '| Diamond (Decision) | ' + BT + 'A{Decision?}' + BT + ' | Branch logic |',
        '| Stadium (Data Store) | ' + BT + 'A([Data Store])' + BT + ' | Databases, files, queues |',
        '| Person icon | ' + BT + 'A(((User)))' + BT + ' | Personas, users, actors |',
        '',
        '---',
        '',
        '## Shape Catalog & Theme References',
        '',
        'Before generating any Lucid diagram, load these project references:',
        '',
        '1. **Shape Catalog** — ' + BT + '.setup-agents/references/lucid-shape-catalog.md' + BT,
        '   Contains: shape class → Salesforce product mapping, swimlane role archetypes,',
        '   flow phase patterns, connector patterns, architecture diagram patterns,',
        '   Standard Import format mapping (export class → import type).',
        '',
        '2. **Color Theme** — resolve in this order:',
        '   - ' + BT + '.setup-agents/diagram-theme.json' + BT + ' (project override — if exists, use it)',
        '   - ' + BT + '.setup-agents/references/diagram-theme.defaults.json' + BT + ' (Salesforce Architect defaults)',
        '',
        '   Apply resolved palette values to shape ' +
            BT +
            'style.fill' +
            BT +
            ', ' +
            BT +
            'style.stroke' +
            BT +
            ', line ' +
            BT +
            'stroke.color' +
            BT +
            ',',
        '   and swimlane ' + BT + 'headerFill' + BT + '/' + BT + 'laneFill' + BT + ' properties.',
        '',
        '3. **Standard Import Spec** — if cached at ' +
            BT +
            '.setup-agents/references/lucid-standard-import-spec.md' +
            BT +
            ',',
        '   read it for type registry, container rules, and endpoint formats.',
        '',
        '---',
        '',
        '## Lucidchart Integration',
        '',
        '### Option A: Lucid MCP Server (Recommended)',
        '',
        'If the Lucid MCP integration is configured (authenticated via Setup Agents UI),',
        'the agent can create and manage Lucidchart documents directly.',
        '',
        '**MANDATORY — Schema-first workflow (always follow this order):**',
        '',
        '1. **Inspect the schema** — call `tools/list` on the Lucid MCP and locate the',
        '   `create_document` tool definition. Read the input schema carefully:',
        '   field names, required fields, nested structures, and accepted value types.',
        '   Never assume field names — derive them from the live schema every time.',
        '',
        '2. **Build the full payload in memory** — using the schema from step 1, construct',
        '   a single JSON object that represents the complete diagram:',
        '   - All pages (if multi-page — see below)',
        '   - All shapes, groups, swim lanes, and color bands',
        '   - All connections and their labels',
        '   - Layout hints (' + BT + 'use_assisted_layout: true' + BT + ' if the schema exposes it)',
        '   - **Shape selection:** use ' + BT + '.setup-agents/references/lucid-shape-catalog.md' + BT + ' to pick',
        '     the correct shape type/class for each Salesforce product or flow element.',
        '   - **Colors:** read the resolved theme (project override or defaults) and apply palette',
        '     values — never hardcode hex colors directly.',
        '   Apply Salesforce design token constraints (see Lucid Diagram Standards in your profile rules)',
        '   while building: colors, notation, and typography go into the payload fields, not as',
        '   post-creation edits.',
        '',
        '3. **Generate SVG preview** — before calling Lucid, render a local SVG for user approval:',
        '   - Convert the payload structure to a Mermaid flowchart (semantic approximation)',
        '   - Render with: ' + BT + 'npx -y @mermaid-js/mermaid-cli -i preview.mmd -o preview.svg' + BT,
        '   - Show the SVG to the user and ask for confirmation before proceeding',
        '   - If the user requests changes, iterate on the payload and re-render the preview',
        '   - Only proceed to step 4 after explicit user approval',
        '',
        '   The preview is a semantic approximation — it will not match Lucid pixel-for-pixel,',
        '   but it validates structure, node count, labels, connections, and flow direction.',
        '',
        '4. **Call `create_document` once** with the approved payload from step 3.',
        '   Never create shapes individually and connect them in separate calls.',
        '',
        '5. **Verify the result explicitly** — check the response for errors.',
        '   Throttle errors from the Lucid MCP can be silent; always inspect the response body.',
        '',
        '6. **Run the post-write validation cycle (MANDATORY)** — see below.',
        '',
        '**Post-Write Validation Cycle (MANDATORY after every batch of write operations):**',
        '',
        'After any `lucid_add_block`, `lucid_add_line`, `lucid_edit_item`, or `lucid_delete_items` call:',
        '',
        '1. Re-fetch the affected page items with a fresh `lucid_get_document` or item-list call.',
        '',
        '2. Run these assertions against the fetched data:',
        '',
        '   | Check | Rule | Auto-fix |',
        '   |-------|------|----------|',
        '   | **Duplicate detection** | No two items with the same text placed within 200px of each other | Delete the later duplicate |',
        '   | **Icon-text gap** | Every icon/label pair has a gap >= 10px (no overlap) | Reposition label +20px from icon edge |',
        '   | **Bounds check** | All labels fit within their container/column width | Truncate or widen container |',
        '   | **Phantom text** | No items whose text matches known fallback patterns (see list below) | Delete or reclassify the element |',
        '   | **Orphan check** | No items with empty text that should have content | Prompt user or delete |',
        '',
        '   Known phantom text patterns:',
        '   - `"aws-general-*"` — AWS shape class not fully resolved',
        '   - `"plugin-flowchart-shape-*"` — Lucid plugin shape fallback',
        '   - `"Type something"` — unfilled text placeholder',
        '   - `"AdvancedSwimLaneBlock"` — invisible swim lane container rendered as text',
        '',
        '3. Export a PNG snapshot after validation:',
        '',
        FENCE + 'bash',
        '# Visual verification artifact — attach to evidence if workflow is active',
        '# lucid_export_document_as_PNG(document_id, page_index)',
        FENCE,
        '',
        '4. If all assertions pass: proceed silently.',
        '   If any assertion fails: auto-fix what is possible, re-export, and report remaining issues to the user.',
        '   Never mark a diagram task complete without a passing validation cycle.',
        '',
        '**Multi-page diagrams:**',
        '',
        'If the diagram requires multiple pages (e.g., System Landscape + Data Model + Sequence),',
        'represent all pages in the single payload built in step 2.',
        'Check the `create_document` schema for the pages/tabs array structure before building.',
        'Never call `create_document` once per page — that produces separate unlinked documents.',
        '',
        '**Check MCP availability:**',
        '',
        FENCE + 'bash',
        '# In Cursor/Claude Code, list available MCP tools',
        '# Look for: lucid__create_document, lucid__search_documents',
        FENCE,
        '',
        '### Generate a Lucid AI Prompt (MCP not available)',
        '',
        'When the MCP is not available, generate a structured prompt for the Lucidchart AI assistant:',
        '',
        FENCE + 'text',
        'Create a [DIAGRAM_TYPE] diagram for a Salesforce [DOMAIN] implementation.',
        '',
        'Use the Salesforce Shape Library (Lucidchart has this built-in — enable it from',
        'the shape panel on the left). Apply these conventions:',
        '- Salesforce orgs: cloud shapes',
        '- External systems: rectangles with a top-color band',
        '- Integrations: labeled arrows with protocol (REST/SOAP/Event)',
        '- Color coding: Salesforce blue (#1798c1) for SF components, grey (#6b7280) for external',
        '',
        'Components to include:',
        '[PASTE YOUR MERMAID DIAGRAM OR COMPONENT LIST HERE]',
        '',
        'Layout: [left-to-right / top-to-bottom]',
        'Audience: [technical / executive]',
        FENCE,
        '',
        '**How to use:**',
        '1. Open Lucidchart → New Document → blank canvas',
        '2. Click the AI panel (sparkle icon) → "Generate diagram"',
        '3. Paste the prompt above with the actual diagram content filled in',
        '4. Lucid AI creates an editable diagram using the Salesforce Shape Library',
        '',
        '### Salesforce Shape Library in Lucidchart',
        '',
        'Lucidchart includes the official Salesforce shape library:',
        '1. Open any Lucidchart document',
        '2. Shape panel (left) → **"Search shapes"** → type "Salesforce"',
        '3. Click **"Use shape library"** → enables all official Salesforce icons and components',
        '',
        'Available shape sets: Salesforce Core Objects, Experience Cloud, Marketing Cloud,',
        'AppExchange logos, and standard system/integration shapes from the Kit of Parts.',
        '',
        '### Script-Based Export (Fallback)',
        '',
        FENCE + 'bash',
        '# Auto-detect target (checks LUCID_ACCESS_TOKEN, falls back to drawio, then local)',
        'bash .setup-agents/skills/diagram-export/scripts/export-diagram.sh diagram.mmd',
        '',
        '# Explicit targets',
        'bash .setup-agents/skills/diagram-export/scripts/export-diagram.sh diagram.mmd --target lucid --title "Solution Architecture"',
        'bash .setup-agents/skills/diagram-export/scripts/export-diagram.sh diagram.mmd --target drawio',
        'bash .setup-agents/skills/diagram-export/scripts/export-diagram.sh diagram.mmd --target local --format pdf',
        FENCE,
        '',
        '---',
        '',
        '## Target: draw.io',
        '',
        'Generates a ' +
            BT +
            '.drawio' +
            BT +
            ' file that opens in [draw.io Desktop](https://www.drawio.com/) or [diagrams.net](https://app.diagrams.net).',
        'No authentication required.',
        '',
        FENCE + 'bash',
        '# Install converter for higher fidelity (optional)',
        'npm install -g mermaid-to-drawio',
        FENCE,
        '',
        '---',
        '',
        '## Target: Local SVG / PDF',
        '',
        FENCE + 'bash',
        '# SVG output (validates syntax as a side effect)',
        'npx -y @mermaid-js/mermaid-cli -i diagram.mmd -o diagram.svg',
        '',
        '# PDF output',
        'bash .setup-agents/skills/story-mapping/scripts/render-pdf.sh diagram.mmd diagram.pdf',
        FENCE,
        '',
        '---',
        '',
        '## Token-Efficient Visual Editing (CRITICAL)',
        '',
        "When generating or updating diagrams, **always push to the user's visual tool** instead of iterating via chat.",
        '',
        '- **DO:** Generate → validate → export → tell user: *"I\'ve pushed to [tool]. Adjust layout, colors, and positions there."*',
        '- **DO NOT:** Accept "move this box right" or "change color of X" via chat. Redirect to the tool.',
        '- **Exception:** Structural changes (add/remove nodes, rename, change relationships) are valid agent tasks.',
        '',
        'If no tool is configured, suggest [Mermaid Live Editor](https://mermaid.live) as a free instant preview.',
        '',
    ].join('\n');
}
export function exportDiagramScript() {
    return [
        '#!/usr/bin/env bash',
        '# Validates Mermaid syntax and exports to Lucidchart, draw.io, or local SVG/PDF.',
        '#',
        '# Usage: export-diagram.sh <input.mmd> [--target lucid|drawio|local] [--title "Title"] [--format svg|pdf]',
        '# Lint-only: export-diagram.sh <input.mmd> --lint',
        '# Auto-detection: LUCID_ACCESS_TOKEN set → lucid, else → drawio, else → local',
        'set -euo pipefail',
        '',
        '# ── Dependency guard ─────────────────────────────────────────────────────',
        'if ! command -v npx &>/dev/null; then',
        '  echo "ERROR: npx not found. Install Node.js >= 18 from https://nodejs.org"',
        '  exit 1',
        'fi',
        '',
        '# ── Parse arguments ──────────────────────────────────────────────────────',
        'INPUT=""',
        'TARGET=""',
        'TITLE=""',
        'FORMAT="svg"',
        'LINT_ONLY=false',
        '',
        'while [[ $# -gt 0 ]]; do',
        '  case "$1" in',
        '    --target)    TARGET="$2"; shift 2 ;;',
        '    --title)     TITLE="$2";  shift 2 ;;',
        '    --format)    FORMAT="$2"; shift 2 ;;',
        '    --lint)      LINT_ONLY=true; shift ;;',
        '    -*)          echo "Unknown option: $1"; exit 1 ;;',
        '    *)           INPUT="$1"; shift ;;',
        '  esac',
        'done',
        '',
        'if [ -z "$INPUT" ]; then',
        '  echo "Usage: export-diagram.sh <input.mmd> [--target lucid|drawio|local] [--title \\"Title\\"] [--format svg|pdf]"',
        '  echo "       export-diagram.sh <input.mmd> --lint"',
        '  exit 1',
        'fi',
        '',
        'if [ ! -f "$INPUT" ]; then',
        '  echo "ERROR: Input file not found: $INPUT"',
        '  exit 1',
        'fi',
        '',
        '[ -z "$TITLE" ] && TITLE="$(basename "$INPUT" .mmd)"',
        '',
        '# ── Puppeteer browser path ────────────────────────────────────────────────',
        '# npx runs mermaid-cli in an isolated cache without access to the system',
        '# Puppeteer browser. Resolve the most recent installed Chrome for Testing.',
        'PUPPETEER_CACHE="${PUPPETEER_CACHE:-$HOME/.cache/puppeteer}"',
        'CHROME_BIN="$(find "$PUPPETEER_CACHE/chrome" -name "Google Chrome for Testing" -type f 2>/dev/null | sort -V | tail -1 || true)"',
        'if [ -n "$CHROME_BIN" ]; then',
        '  export PUPPETEER_EXECUTABLE_PATH="$CHROME_BIN"',
        'fi',
        '',
        '# ── Mermaid syntax validation (linter) ───────────────────────────────────',
        '# mmdc exits non-zero on parse errors — this IS the linter.',
        '# Run to a temp SVG so we get real error messages without keeping the file.',
        'echo "Validating Mermaid syntax in $INPUT ..."',
        'SVG_TMP="$(mktemp /tmp/mermaid-lint-XXXXXX.svg)"',
        '',
        'if ! npx -y @mermaid-js/mermaid-cli -i "$INPUT" -o "$SVG_TMP" --quiet 2>&1; then',
        '  echo ""',
        '  echo "─────────────────────────────────────────"',
        '  echo "LINT FAILED: Invalid Mermaid syntax in $INPUT"',
        '  echo "Fix the error shown above before exporting."',
        '  echo "─────────────────────────────────────────"',
        '  rm -f "$SVG_TMP"',
        '  exit 1',
        'fi',
        '',
        '# Extra sanity: reject suspiciously small SVGs and known error text',
        'SVG_SIZE=$(wc -c < "$SVG_TMP" | tr -d " ")',
        'if [ "$SVG_SIZE" -lt 512 ]; then',
        '  echo "WARN: Rendered SVG is very small (${SVG_SIZE} bytes) — may indicate a rendering problem."',
        'fi',
        'if grep -qiE "No diagram detected|Parse error|UnknownDiagramError" "$SVG_TMP" 2>/dev/null; then',
        '  echo "ERROR: SVG output contains error text — diagram was not rendered correctly."',
        '  rm -f "$SVG_TMP"',
        '  exit 1',
        'fi',
        '',
        'echo "✓ Mermaid syntax OK"',
        '',
        'if [ "$LINT_ONLY" = true ]; then',
        '  rm -f "$SVG_TMP"',
        '  exit 0',
        'fi',
        '',
        '# ── Auto-detect target ───────────────────────────────────────────────────',
        'if [ -z "$TARGET" ]; then',
        '  if [ -n "${LUCID_ACCESS_TOKEN:-}" ]; then',
        '    TARGET="lucid"',
        '  elif command -v mermaid-to-drawio &>/dev/null; then',
        '    TARGET="drawio"',
        '  else',
        '    TARGET="local"',
        '  fi',
        '  echo "Auto-detected target: $TARGET"',
        'fi',
        '',
        '# ── Target: local ───────────────────────────────────────────────────────',
        'if [ "$TARGET" = "local" ]; then',
        '  OUTPUT="${INPUT%.mmd}.$FORMAT"',
        '  if [ "$FORMAT" = "pdf" ]; then',
        '    STORY_CSS="$(cd "$(dirname "$0")/../../story-mapping/assets" 2>/dev/null && pwd)/mermaid-pdf.css" || true',
        '    CSS_FLAG=""',
        '    [ -f "${STORY_CSS:-}" ] && CSS_FLAG="--cssFile $STORY_CSS"',
        '    # shellcheck disable=SC2086',
        '    npx -y @mermaid-js/mermaid-cli -i "$INPUT" -o "$OUTPUT" $CSS_FLAG --pdfFit',
        '  else',
        '    cp "$SVG_TMP" "$OUTPUT"',
        '  fi',
        '  rm -f "$SVG_TMP"',
        '  echo "Exported to $OUTPUT"',
        '  exit 0',
        'fi',
        '',
        '# ── Build draw.io file (needed for drawio + lucid targets) ───────────────',
        'DRAWIO_FILE="${INPUT%.mmd}.drawio"',
        '',
        'if [ "$TARGET" = "drawio" ] || [ "$TARGET" = "lucid" ]; then',
        '  if command -v mermaid-to-drawio &>/dev/null; then',
        '    echo "Converting to draw.io format..."',
        '    mermaid-to-drawio "$INPUT" -o "$DRAWIO_FILE"',
        '  else',
        '    echo "Wrapping SVG in draw.io XML envelope..."',
        '    SVG_CONTENT=$(cat "$SVG_TMP")',
        '    cat > "$DRAWIO_FILE" <<XMLEOF',
        '<?xml version="1.0" encoding="UTF-8"?>',
        '<mxfile>',
        '  <diagram name="$TITLE">',
        '    <mxGraphModel>',
        '      <root>',
        '        <mxCell id="0"/>',
        '        <mxCell id="1" parent="0"/>',
        '        <mxCell id="2" value="" style="shape=image;image=data:image/svg+xml,${SVG_CONTENT}" vertex="1" parent="1">',
        '          <mxGeometry width="800" height="600" as="geometry"/>',
        '        </mxCell>',
        '      </root>',
        '    </mxGraphModel>',
        '  </diagram>',
        '</mxfile>',
        'XMLEOF',
        '  fi',
        'fi',
        '',
        'rm -f "$SVG_TMP"',
        '',
        '# ── Target: drawio ──────────────────────────────────────────────────────',
        'if [ "$TARGET" = "drawio" ]; then',
        '  echo "Exported to $DRAWIO_FILE — open with draw.io or diagrams.net"',
        '  exit 0',
        'fi',
        '',
        '# ── Target: lucid ───────────────────────────────────────────────────────',
        'if [ -z "${LUCID_ACCESS_TOKEN:-}" ]; then',
        '  echo "WARN: LUCID_ACCESS_TOKEN not set. Falling back to draw.io export."',
        '  echo "Exported to $DRAWIO_FILE — open with draw.io or diagrams.net"',
        '  exit 0',
        'fi',
        '',
        'echo "Pushing to Lucidchart..."',
        'RESPONSE=$(curl -s -w "\\n%{http_code}" -X POST "https://api.lucid.co/documents" \\',
        '  -H "Authorization: Bearer ${LUCID_ACCESS_TOKEN}" \\',
        '  -H "Lucid-Api-Version: 1" \\',
        '  -F "title=${TITLE}" \\',
        '  -F "product=lucidchart" \\',
        '  -F "file=@${DRAWIO_FILE};type=x-application/vnd.lucid.drawio")',
        '',
        'HTTP_CODE=$(echo "$RESPONSE" | tail -1)',
        'BODY=$(echo "$RESPONSE" | sed \'$d\')',
        '',
        'if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "201" ]; then',
        '  echo "✓ Document created in Lucidchart."',
        '  echo "$BODY"',
        'elif [ "$HTTP_CODE" = "401" ]; then',
        '  echo "ERROR: Authentication failed (401). Re-authenticate via Setup Agents UI."',
        '  echo "Fallback: draw.io file available at $DRAWIO_FILE"',
        'else',
        '  echo "ERROR: Lucid API returned HTTP $HTTP_CODE"',
        '  echo "$BODY"',
        '  exit 1',
        'fi',
        '',
    ].join('\n');
}
//# sourceMappingURL=diagram-export-content.js.map