#!/usr/bin/env bash
# Fetch an Azure DevOps work item as clean JSON.
#
# Usage: fetch_workitem.sh <workItemId>
#
# Prints to stdout:
#   { "id", "type", "title", "state", "description", "acceptanceCriteria",
#     "childWorkItems": [ids...], "url" }
#
# description and acceptanceCriteria come back as plain text (HTML stripped).
# childWorkItems lists every child (System.LinkTypes.Hierarchy-Forward). Set
# AZURE_ASSIGNEE=<user@domain> to keep only the children assigned to that person.
#
# Config via load_env.sh (env or .env). The PAT is never printed.
# Requires: curl, python3 (or python).
set -euo pipefail

ID="${1:?Usage: fetch_workitem.sh <workItemId>}"
[[ "$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)"
export PYTHONIOENCODING=utf-8
ASSIGNEE="${AZURE_ASSIGNEE:-}"

main_json="$(curl -s -u ":$PAT" "$BASE_URL/_apis/wit/workitems/$ID?\$expand=relations&$API")"
assert_json "$main_json" "work item $ID" || exit 1

child_ids="$(printf '%s' "$main_json" | "$PY" -c '
import sys, json, re
d = json.load(sys.stdin)
if "fields" not in d:
    sys.stderr.write("ERROR: %s\n" % (d.get("message") or "work item not found"))
    sys.exit(2)
ids = []
for r in d.get("relations") or []:
    if r.get("rel") == "System.LinkTypes.Hierarchy-Forward":
        m = re.search(r"/(\d+)$", r.get("url", ""))
        if m:
            ids.append(m.group(1))
print(" ".join(ids))
' | tr -d '\r')"

kept=()
for cid in $child_ids; do
  if [[ -z "$ASSIGNEE" ]]; then kept+=("$cid"); continue; fi
  cjson="$(curl -s -u ":$PAT" "$BASE_URL/_apis/wit/workitems/$cid?fields=System.AssignedTo&$API")"
  who="$(printf '%s' "$cjson" | "$PY" -c '
import sys, json
try:
    a = (json.load(sys.stdin).get("fields") or {}).get("System.AssignedTo") or {}
    print((a.get("uniqueName") or a.get("mail") or "").lower())
except Exception:
    print("")
' | tr -d '\r')"
  if [[ "$who" == "$(printf '%s' "$ASSIGNEE" | tr '[:upper:]' '[:lower:]')" ]]; then kept+=("$cid"); fi
done

printf '%s' "$main_json" | KEPT="${kept[*]:-}" WI_ID="$ID" WI_URL="$BASE_URL/_workitems/edit/$ID" "$PY" -c '
import sys, json, os, re, html
d = json.load(sys.stdin)
f = d.get("fields") or {}
def strip(s):
    if not s:
        return ""
    s = re.sub(r"<\s*(br|/p|/div|/li)\s*/?>", "\n", s, flags=re.I)
    s = re.sub(r"<li[^>]*>", "- ", s, flags=re.I)
    s = re.sub(r"<[^>]+>", "", s)
    s = html.unescape(s).replace("\xa0", " ")
    s = re.sub(r"[ \t]+", " ", s)
    return re.sub(r"\n\s*\n+", "\n", s).strip()
print(json.dumps({
    "id": os.environ["WI_ID"],
    "type": f.get("System.WorkItemType", ""),
    "title": f.get("System.Title", ""),
    "state": f.get("System.State", ""),
    "description": strip(f.get("System.Description", "")),
    "acceptanceCriteria": strip(f.get("Microsoft.VSTS.Common.AcceptanceCriteria", "")),
    "childWorkItems": [x for x in os.environ.get("KEPT", "").split() if x],
    "url": os.environ["WI_URL"],
}, ensure_ascii=False, indent=2))
'
