#!/usr/bin/env bash
# Explicit source-context export helper for fresh installs.
#
# Markdown remains an export format; cogitod source_context_* tools are the source
# of truth. This helper gives installed users one local command without requiring
# them to know the MCP JSON-RPC shape.
set -euo pipefail

usage() {
  cat <<'EOF'
usage: source-context-export [path] [--output DIR] [--views a,b,c]

Exports cogitod source-context markdown for the git repo at path, or $PWD.
Default output: ~/.cogito/breathe/source-context/<repo>
EOF
}

TARGET_PATH="$PWD"
OUTPUT_DIR=""
VIEWS=""

while [ "$#" -gt 0 ]; do
  case "$1" in
    -h|--help) usage; exit 0 ;;
    --output)
      [ "$#" -ge 2 ] || { echo "--output requires a directory" >&2; exit 2; }
      OUTPUT_DIR="$2"; shift 2 ;;
    --views)
      [ "$#" -ge 2 ] || { echo "--views requires a comma-separated list" >&2; exit 2; }
      VIEWS="$2"; shift 2 ;;
    --*) echo "unknown option: $1" >&2; usage >&2; exit 2 ;;
    *) TARGET_PATH="$1"; shift ;;
  esac
done

command -v curl >/dev/null 2>&1 || { echo "curl is required" >&2; exit 1; }
command -v python3 >/dev/null 2>&1 || { echo "python3 is required" >&2; exit 1; }

BASE="${BREATHE_MCP_ENDPOINT:-http://127.0.0.1:${BREATHE_PORT:-24567}}"
BASE="${BASE%%/mcp*}"
URL="$BASE/mcp?profile=app"

PAYLOAD="$(python3 - "$TARGET_PATH" "$OUTPUT_DIR" "$VIEWS" <<'PY'
import json, sys
path, output, views = sys.argv[1:4]
args = {"path": path}
if output:
    args["output_dir"] = output
if views:
    args["views"] = [v.strip() for v in views.split(",") if v.strip()]
print(json.dumps({
    "jsonrpc": "2.0",
    "id": "source-context-export",
    "method": "tools/call",
    "params": {"name": "source_context_export", "arguments": args},
}))
PY
)"

RESP="$(printf '%s' "$PAYLOAD" | curl -sf --max-time 30 -X POST "$URL" \
  -H 'Content-Type: application/json' --data-binary @-)"

RESP_JSON="$RESP" python3 - <<'PY'
import json, os
body = json.loads(os.environ["RESP_JSON"])
if body.get("error"):
    raise SystemExit(body["error"].get("message") or "MCP error")
result = body.get("result") or {}
if result.get("isError"):
    content = result.get("content") or []
    raise SystemExit((content[0].get("text") if content else None) or "source_context_export failed")
text = ((result.get("content") or [{}])[0]).get("text") or "{}"
data = json.loads(text)
print(data.get("output_dir", "export complete"))
for file in data.get("files", []):
    print(file)
PY
