#!/usr/bin/env bash
# planner-attach — multipart-upload evidence файл к AC, без проводки байтов
# через LLM-context. Альтернатива MCP-инструменту attach-evidence-file для
# любого размера > ~1 KB raw (где base64-путь в JSON-RPC ненадёжен).
#
# Use case (агент через bash):
#   curl -sS "$PLANNER_URL/api/cli/planner-attach.sh" \
#     | PLANNER_TOKEN=... bash -s -- \
#         --criterion-id 019e... --file /abs/path/to/file.png \
#         --caption "что захвачено" --created-by agent-id
#
# Печатает на stdout JSON-ответ сервера (тот же контракт, что у MCP-tool).
set -euo pipefail

PLANNER_URL="${PLANNER_URL:-https://planner.monopoly-gold.com}"
PLANNER_TOKEN="${PLANNER_TOKEN:-${X_AUTH_TOKEN:-}}"

usage() {
    cat >&2 <<EOF
Usage:
  planner-attach.sh --criterion-id <UUID> --file <PATH>
                    [--caption <TEXT>] [--created-by <NAME>] [--kind <KIND>]
                    [--planner-url <URL>]

  --kind session_history  marks the upload as the goal-level «full Claude
                          session transcript» artifact (close gate I4). Such
                          evidence does not cover an AC and is not judged.
                          Omit for normal per-AC proof.

Env:
  PLANNER_URL    default: https://planner.monopoly-gold.com (override via --planner-url)
  PLANNER_TOKEN  required (or X_AUTH_TOKEN). Same value MCP-клиент шлёт в X-Auth-Token.

Output:
  Server JSON response on stdout. Exits non-zero on transport error or HTTP >= 400.

Notes:
  - Computes SHA-256 client-side (sha256sum or shasum -a 256) and ships it as
    multipart field "contentSha256"; server fast-fails with file_hash_mismatch
    if anything in flight corrupted the bytes.
  - MIME determined from libmagic (\`file --mime-type\`) если доступен,
    fallback application/octet-stream — сервер всё равно сниффит сам.
EOF
    exit 2
}

criterion=""
file=""
caption=""
created_by=""
kind=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --criterion-id) criterion="${2:?--criterion-id needs value}"; shift 2 ;;
        --file)         file="${2:?--file needs value}"; shift 2 ;;
        --caption)      caption="${2:?--caption needs value}"; shift 2 ;;
        --created-by)   created_by="${2:?--created-by needs value}"; shift 2 ;;
        --kind)         kind="${2:?--kind needs value}"; shift 2 ;;
        --planner-url)  PLANNER_URL="${2:?--planner-url needs value}"; shift 2 ;;
        -h|--help)      usage ;;
        *)              echo "planner-attach: unknown arg: $1" >&2; usage ;;
    esac
done

[[ -n "$criterion" ]]      || { echo "planner-attach: --criterion-id is required" >&2; exit 2; }
[[ -n "$file" ]]           || { echo "planner-attach: --file is required" >&2; exit 2; }
[[ -f "$file" ]]           || { echo "planner-attach: file not found: $file" >&2; exit 2; }
[[ -n "$PLANNER_TOKEN" ]]  || { echo "planner-attach: PLANNER_TOKEN env is required (same X-Auth-Token used by MCP)" >&2; exit 2; }

if command -v sha256sum >/dev/null 2>&1; then
    sha=$(sha256sum -- "$file" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
    sha=$(shasum -a 256 -- "$file" | awk '{print $1}')
else
    echo "planner-attach: need sha256sum or shasum on PATH" >&2
    exit 1
fi

if command -v file >/dev/null 2>&1; then
    mime=$(file --brief --mime-type -- "$file" 2>/dev/null || echo "application/octet-stream")
else
    mime="application/octet-stream"
fi
[[ -n "$mime" ]] || mime="application/octet-stream"

args=(
    --silent --show-error
    --write-out '\nHTTP_STATUS=%{http_code}\n'
    -X POST
    -H "X-Auth-Token: $PLANNER_TOKEN"
    -F "file=@${file};type=${mime}"
    -F "contentSha256=$sha"
)
[[ -n "$caption" ]]    && args+=( -F "caption=$caption" )
[[ -n "$created_by" ]] && args+=( -F "createdBy=$created_by" )
[[ -n "$kind" ]]       && args+=( -F "kind=$kind" )

raw=$(curl "${args[@]}" "$PLANNER_URL/api/criteria/$criterion/evidence/file") || {
    rc=$?
    echo "planner-attach: curl failed (exit $rc)" >&2
    exit "$rc"
}

# Split off the trailing HTTP_STATUS line written by --write-out so the rest
# is clean JSON.
http_status=$(printf '%s\n' "$raw" | awk -F= '/^HTTP_STATUS=/{print $2}' | tail -1)
body=$(printf '%s\n' "$raw" | sed '/^HTTP_STATUS=/d')

printf '%s\n' "$body"

if [[ "$http_status" =~ ^2 ]]; then
    exit 0
fi
echo "planner-attach: HTTP $http_status (body printed above)" >&2
exit 1
