#!/bin/sh
# bin/connect — optional: register BaoCut as an MCP server (macOS / Linux).
#
# The skill works over the CLI (bin/bcut-cli) without this. Run it only when
# the user wants the Agent to talk to BaoCut through MCP as well: it resolves
# the same `bcut` that bin/bcut-cli uses, checks that App and CLI agree on
# their version, and asks that CLI to register itself in the Agent's MCP
# configuration (`bcut mcp install --agent <name>`).
#
# Exit codes: 0 registered (or already registered); 2 usage / agent unknown;
# 3 no BaoCut App found (stdout carries a structured `app_not_installed`
# guide; run bin/install-app after telling the user); 4 App and CLI disagree.
#
# Options:
#   --agent <claude-code|codex|cursor|gemini>  which Agent's config to write
#                                              (default: detected from env)
#   --print                                    only print the resolved CLI, do not install
#   --json                                     machine-readable stdout
# Environment overrides (rarely needed): BAOCUT_CLI / BCUT_EXECUTABLE /
# BAOCUT_BIN (explicit CLI), BAOCUT_APP (explicit .app bundle), BAOCUT_SKILL_NO_DEV=1
# (ignore a development checkout around this skill).
set -eu

skill_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd -P)

agent=
print_only=0
json=0
while [ $# -gt 0 ]; do
    case "$1" in
        --agent) agent=${2:-}; shift 2 ;;
        --agent=*) agent=${1#--agent=}; shift ;;
        --print) print_only=1; shift ;;
        --json) json=1; shift ;;
        -h|--help)
            sed -n '2,24p' "$0" | sed 's/^# \{0,1\}//'
            exit 0 ;;
        *) echo "connect: unknown argument $1" >&2; exit 2 ;;
    esac
done

plist_version() {
    # CFBundleShortVersionString from an Info.plist (both one-line and two-line layouts).
    tr -d '\n' < "$1" | sed -n 's/.*<key>CFBundleShortVersionString<\/key>[[:space:]]*<string>\([^<]*\)<\/string>.*/\1/p'
}

# CLI resolution lives in bin/bcut-cli (the skill's command entry); this
# script only adds the MCP registration on top of it.
if ! resolved=$("$skill_root/bin/bcut-cli" --print --json); then
    status=$?
    # bin/bcut-cli's structured guide (e.g. app_not_installed) stays on stdout.
    [ -n "$resolved" ] && printf '%s\n' "$resolved"
    exit "$status"
fi
cli=$(printf '%s\n' "$resolved" | sed -n 's/.*"cli":"\([^"]*\)".*/\1/p')
cli_source=$(printf '%s\n' "$resolved" | sed -n 's/.*"source":"\([^"]*\)".*/\1/p')
app_bundle=$(printf '%s\n' "$resolved" | sed -n 's/.*"appBundle":"\([^"]*\)".*/\1/p')
if [ -z "$cli" ]; then
    echo "connect: bin/bcut-cli did not report a CLI: $resolved" >&2
    exit 3
fi

# The CLI must be the App's own build: compare the bundle's marketing version
# with what the binary reports. A mismatch means a partially replaced install.
cli_version=$("$cli" --json version 2>/dev/null | sed -n 's/.*"appVersion":"\([^"]*\)".*/\1/p' | head -n 1)
if [ -n "$app_bundle" ] && [ -f "$app_bundle/Contents/Info.plist" ]; then
    bundle_version=$(plist_version "$app_bundle/Contents/Info.plist")
    if [ -n "$bundle_version" ] && [ -n "$cli_version" ] && [ "$bundle_version" != "$cli_version" ]; then
        echo "connect: $app_bundle is version $bundle_version but its bcut reports $cli_version; the installation is damaged — reinstall the App." >&2
        exit 4
    fi
fi

if [ "$print_only" = 1 ]; then
    if [ "$json" = 1 ]; then
        printf '{"ok":true,"cli":"%s","source":"%s","appVersion":"%s"}\n' "$cli" "$cli_source" "$cli_version"
    else
        echo "$cli"
    fi
    exit 0
fi

# Which Agent are we inside? Explicit --agent wins; otherwise the hosts' own
# environment markers.
if [ -z "$agent" ]; then
    if [ -n "${CLAUDECODE:-}" ] || [ -n "${CLAUDE_CODE_ENTRYPOINT:-}" ]; then agent=claude-code
    elif [ -n "${CODEX_SANDBOX:-}" ] || [ -n "${CODEX_HOME:-}" ] || [ -n "${CODEX_THREAD_ID:-}" ]; then agent=codex
    elif [ -n "${CURSOR_TRACE_ID:-}" ] || [ -n "${CURSOR_AGENT:-}" ]; then agent=cursor
    elif [ -n "${GEMINI_CLI:-}" ] || [ -n "${GEMINI_API_KEY:-}" ]; then agent=gemini
    fi
fi
if [ -z "$agent" ]; then
    echo "connect: cannot tell which Agent this is; rerun with --agent claude-code|codex|cursor|gemini" >&2
    exit 2
fi

set -- mcp install --agent "$agent"
[ "$json" = 1 ] && set -- "$@" --json
if ! "$cli" "$@"; then
    status=$?
    echo "connect: '$cli mcp install --agent $agent' failed (exit $status)" >&2
    exit "$status"
fi
if [ "$json" != 1 ]; then
    echo "Registered the 'baocut' MCP server for $agent using $cli. Reload MCP servers / restart the Agent; then call serve_status and continue with SKILL.md." >&2
fi
exit 0
