#!/usr/bin/env bash
# Create an Azure DevOps work item (PBI or Bug) from a triaged Jira ticket.
#
# Usage:
#   create_workitem.sh --type pbi|bug --jira <JIRA-KEY> --title <title> \
#                      --description-file <file> [--ac-file <file>] \
#                      [--tags "a; b"] [--area '<AreaPath>'] \
#                      [--env <name>] [--field Ref.Name=value ...] [--dry-run]
#
# ALWAYS run once with --dry-run first, show the payload and get an explicit
# confirmation: a new work item is visible to the whole team.
#
# The Jira ticket is linked with a Hyperlink relation, which every process
# template accepts, instead of a custom field.
#
# Process templates differ. Fields your template requires on create go in with
# --field, repeatable:
#   --field Microsoft.VSTS.Common.Priority=2 --field Custom.SomeFlag=false
# Values true/false and integers are sent as JSON booleans/numbers.
#
#   --area   defaults to AZURE_AREA_PATH (env / .env); omitted if neither is set,
#            so the project's default area applies.
#   --env    affected environment (e.g. PRO, PRE). Written to the field named by
#            AZURE_ENV_FIELD; ignored with a warning if that is not set.
#
# Never put personal data in the title or description (references/pii.md).
#
# Reads PAT / ORG / PROJECT and JIRA_BASE_URL through load_env.sh.
# The PAT needs Work Items (Read & Write). Prints "<id>\t<url>" on success.
# Requires: curl, python3 (or python).
set -euo pipefail

API="api-version=7.1"

TYPE=""; JIRA_KEY=""; TITLE=""; DESC_FILE=""; AC_FILE=""
ENV_NAME=""; TAGS=""; AREA=""; DRY_RUN="no"; EXTRA_FIELDS=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    --type)             TYPE="${2:?}"; shift 2 ;;
    --jira)             JIRA_KEY="${2:?}"; shift 2 ;;
    --title)            TITLE="${2:?}"; shift 2 ;;
    --description-file) DESC_FILE="${2:?}"; shift 2 ;;
    --ac-file)          AC_FILE="${2:?}"; shift 2 ;;
    --env)              ENV_NAME="${2:?}"; shift 2 ;;
    --tags)             TAGS="${2:?}"; shift 2 ;;
    --area)             AREA="${2:?}"; shift 2 ;;
    --field)            EXTRA_FIELDS+=("${2:?}"); shift 2 ;;
    --dry-run)          DRY_RUN="yes"; shift ;;
    *) echo "ERROR: unknown argument '$1'" >&2; exit 1 ;;
  esac
done

[[ -n "$TYPE"      ]] || { echo "ERROR: --type pbi|bug is required" >&2; exit 1; }
[[ -n "$JIRA_KEY"  ]] || { echo "ERROR: --jira <JIRA-KEY> is required" >&2; exit 1; }
[[ -n "$TITLE"     ]] || { echo "ERROR: --title <title> is required" >&2; exit 1; }
[[ -n "$DESC_FILE" ]] || { echo "ERROR: --description-file <file> is required" >&2; exit 1; }

case "$(printf '%s' "$TYPE" | tr '[:upper:]' '[:lower:]')" in
  pbi) WIT="Product Backlog Item" ;;
  bug) WIT="Bug" ;;
  *) echo "ERROR: --type must be 'pbi' or 'bug'" >&2; exit 1 ;;
esac

[[ -f "$DESC_FILE" ]] || { echo "ERROR: file '$DESC_FILE' not found" >&2; exit 1; }
[[ -z "$AC_FILE" || -f "$AC_FILE" ]] || { echo "ERROR: file '$AC_FILE' not found" >&2; exit 1; }

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

[[ -n "$AREA" ]] || AREA="$(_env_lookup AZURE_AREA_PATH)"
ENV_FIELD="$(_env_lookup AZURE_ENV_FIELD)"
if [[ -n "$ENV_NAME" && -z "$ENV_FIELD" ]]; then
  echo "WARN: --env given but AZURE_ENV_FIELD is not set; the environment goes only in the description." >&2
fi

JIRA_BROWSE=""
if [[ -n "${JIRA_BASE_URL:-}" ]]; then
  JIRA_BROWSE="$JIRA_BASE_URL/browse/$JIRA_KEY"
else
  echo "WARN: JIRA_BASE_URL not set; the work item will carry no link to $JIRA_KEY." >&2
fi

PY="$(command -v python3 || command -v python || true)"
[[ -n "$PY" ]] || { echo "ERROR: python3 is required" >&2; exit 1; }
export PYTHONIOENCODING=utf-8

fields_blob="$(printf '%s\n' "${EXTRA_FIELDS[@]+"${EXTRA_FIELDS[@]}"}")"

payload="$(WIT="$WIT" TITLE="$TITLE" DESC_FILE="$DESC_FILE" AC_FILE="$AC_FILE" \
  AREA="$AREA" TAGS="$TAGS" ENV_NAME="$ENV_NAME" ENV_FIELD="$ENV_FIELD" \
  JIRA_BROWSE="$JIRA_BROWSE" EXTRA="$fields_blob" "$PY" -c "
import os, json, html, re, sys

def to_html(text):
    # Azure renders these fields as HTML; keep it minimal: paragraphs and lists.
    blocks, buf = [], []
    for line in text.replace('\r\n', '\n').split('\n'):
        if line.strip():
            buf.append(line)
        elif buf:
            blocks.append(buf); buf = []
    if buf:
        blocks.append(buf)
    out = []
    for b in blocks:
        if all(re.match(r'\s*[-*]\s+', l) for l in b):
            items = ''.join('<li>%s</li>' % html.escape(re.sub(r'^\s*[-*]\s+', '', l)) for l in b)
            out.append('<ul>%s</ul>' % items)
        else:
            out.append('<p>%s</p>' % '<br>'.join(html.escape(l) for l in b))
    return ''.join(out) or '<p></p>'

def read(path):
    with open(path, encoding='utf-8') as fh:
        return fh.read()

def typed(value):
    v = value.strip()
    if v.lower() in ('true', 'false'):
        return v.lower() == 'true'
    if re.fullmatch(r'-?\d+', v):
        return int(v)
    return value

def add(path, value):
    ops.append({'op': 'add', 'path': path, 'value': value})

ops = []
add('/fields/System.Title', os.environ['TITLE'])
add('/fields/System.Description', to_html(read(os.environ['DESC_FILE'])))
if os.environ.get('AREA'):
    add('/fields/System.AreaPath', os.environ['AREA'])
if os.environ.get('AC_FILE'):
    add('/fields/Microsoft.VSTS.Common.AcceptanceCriteria', to_html(read(os.environ['AC_FILE'])))
if os.environ.get('TAGS'):
    add('/fields/System.Tags', os.environ['TAGS'])
if os.environ.get('ENV_NAME') and os.environ.get('ENV_FIELD'):
    add('/fields/' + os.environ['ENV_FIELD'], os.environ['ENV_NAME'])
for raw in (os.environ.get('EXTRA') or '').splitlines():
    if not raw.strip():
        continue
    if '=' not in raw:
        sys.exit('ERROR: --field expects Ref.Name=value, got %r' % raw)
    name, value = raw.split('=', 1)
    add('/fields/' + name.strip(), typed(value))
if os.environ.get('JIRA_BROWSE'):
    add('/relations/-', {'rel': 'Hyperlink', 'url': os.environ['JIRA_BROWSE']})
print(json.dumps(ops, ensure_ascii=False))
")"

if [[ "$DRY_RUN" == "yes" ]]; then
  echo "DRY RUN - nothing was created. Payload for a '$WIT' in $ORG/$PROJECT:"
  printf '%s' "$payload" | "$PY" -m json.tool
  exit 0
fi

# The type goes in the path prefixed with '$' (url-encoded %24).
wit_encoded="${WIT// /%20}"
url="$BASE_URL/_apis/wit/workitems/%24$wit_encoded?$API"

resp="$(curl -s -u ":$PAT" \
  -H "Content-Type: application/json-patch+json" \
  -X POST "$url" -d "$payload")" || { echo "ERROR: the create request failed" >&2; exit 1; }

new_id="$(printf '%s' "$resp" | "$PY" -c "
import sys, json
try:
    print((json.load(sys.stdin) or {}).get('id') or '')
except Exception:
    print('')
" | tr -d '\r')"

if [[ -z "$new_id" ]]; then
  {
    echo "ERROR: Azure DevOps did not return a work item id."
    if assert_json "$resp" "the create request" 2>/dev/null; then
      printf '%s\n' "$resp" | head -c 1500; echo
    fi
    echo "Common causes:"
    echo "  - the PAT lacks 'Work Items (Read & Write)' (401/403) or has expired"
    echo "  - a field your process template requires on create is missing (add it with --field)"
    echo "  - the area path does not exist: ${AREA:-<project default>}"
    echo "Nothing was created."
  } >&2
  exit 1
fi

printf '%s\t%s\n' "$new_id" "$BASE_URL/_workitems/edit/$new_id"
