#!/usr/bin/env bash
# Attach a plan file (markdown) to an Azure DevOps work item.
#
# Usage: attach_plan.sh <workItemId> <planFile> [comment]
#
#   attach_plan.sh 1234 plan-1234.md
#
# Run it ONLY after the user has confirmed: attaching publishes the plan to the
# whole team. The PAT needs "Work Items (Read & Write)"; read-only PATs fail
# with 401/403 and the script stops without retrying.
#
# Two REST calls (api-version=7.1):
#   1. POST  _apis/wit/attachments?fileName=...  -> returns the attachment url
#   2. PATCH _apis/wit/workitems/<id>            -> adds the "AttachedFile" relation
# The first one alone uploads an orphan file nobody can see.
#
# Config via load_env.sh (env or .env). The PAT is never printed.
# Requires: curl, python3 (or python).
set -euo pipefail

ID="${1:?Usage: attach_plan.sh <workItemId> <planFile> [comment]}"
PLAN_FILE="${2:?Usage: attach_plan.sh <workItemId> <planFile> [comment]}"
COMMENT="${3:-Plan de implementación}"
[[ "$ID" =~ ^[0-9]+$ ]] || { echo "ERROR: '$ID' is not a numeric work item id" >&2; exit 1; }

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=load_env.sh
source "$HERE/load_env.sh"
require_azure || exit 1

API="api-version=7.1"
PY="$(command -v python3 || command -v python)"
WI_URL="$BASE_URL/_workitems/edit/$ID"

if [[ ! -f "$PLAN_FILE" && -f "$ROOT/$PLAN_FILE" ]]; then PLAN_FILE="$ROOT/$PLAN_FILE"; fi
[[ -f "$PLAN_FILE" ]] || { echo "ERROR: plan file '$PLAN_FILE' not found" >&2; exit 1; }
FILE_NAME="$(basename "$PLAN_FILE")"

manual_fallback() {
  {
    echo ""
    echo "ERROR: could not attach the plan to work item $ID ($1)."
    echo "The local file is intact: $PLAN_FILE"
    echo "Common causes:"
    echo "  - the work item does not exist (TF401232)"
    echo "  - the PAT lacks 'Work Items (Read & Write)' (401/403)"
    echo "To attach it by hand: open the work item, Attachments tab, drop the file in:"
    echo "  $WI_URL"
  } >&2
  exit 1
}

up_resp="$(curl -s -u ":$PAT" -H "Content-Type: application/octet-stream" -X POST \
  "$BASE_URL/_apis/wit/attachments?fileName=$FILE_NAME&$API" \
  --data-binary "@$PLAN_FILE")" || manual_fallback "upload request failed"
assert_json "$up_resp" "attachment upload" || manual_fallback "upload did not return JSON"

attachment_url="$(printf '%s' "$up_resp" | "$PY" -c '
import sys, json
try:
    print((json.load(sys.stdin) or {}).get("url", ""))
except Exception:
    print("")
' | tr -d '\r')"
[[ -n "$attachment_url" ]] || manual_fallback "the upload returned no attachment url"

patch_body="$(ATT_URL="$attachment_url" ATT_NAME="$FILE_NAME" ATT_COMMENT="$COMMENT" "$PY" -c '
import os, json
print(json.dumps([{"op": "add", "path": "/relations/-", "value": {
    "rel": "AttachedFile", "url": os.environ["ATT_URL"],
    "attributes": {"name": os.environ["ATT_NAME"], "comment": os.environ["ATT_COMMENT"]}}}]))
')"

patch_resp="$(curl -s -u ":$PAT" -H "Content-Type: application/json-patch+json" -X PATCH \
  "$BASE_URL/_apis/wit/workitems/$ID?$API" -d "$patch_body")" || manual_fallback "link request failed"

linked="$(printf '%s' "$patch_resp" | "$PY" -c '
import sys, json
try:
    print("yes" if (json.load(sys.stdin) or {}).get("id") else "no")
except Exception:
    print("no")
' | tr -d '\r')"
[[ "$linked" == "yes" ]] || manual_fallback "the work item update was rejected"

echo "Attached '$FILE_NAME' to work item $ID"
echo "$WI_URL"
