#!/usr/bin/env bash
# Fetch a Jira Cloud issue plus everything needed to plan against it.
#
# Usage: fetch_issue.sh <issueKeyOrUrlOrNumber>
#
# Accepts: PROJ-1234 | https://<site>.atlassian.net/browse/PROJ-1234
#          | 1234 (only when JIRA_DEFAULT_PROJECT is set)
#
# Reads JIRA_BASE_URL, JIRA_EMAIL and JIRA_API_TOKEN through load_env.sh.
# The token is never printed.
#
# Uses REST API v2 on purpose: it returns description and comments as wiki-markup
# text, whereas v3 returns Atlassian Document Format, far noisier to read.
#
# Prints one JSON object:
#   { key, url, type, status, priority, created, summary, labels, components,
#     description, identifiers, comments[], linkedIssues[], attachments[],
#     subtasks[], parent }
#
# Bodies are CLEANED: wiki-markup noise removed, image macros turned into
# [imagen: file.png] placeholders, pasted-email signatures and legal notices cut.
# Reporter, assignee and comment authors are left out on purpose: a plan needs
# what was said, not who said it (references/pii.md).
#
# identifiers (optional): JIRA_ID_PATTERNS lists the functional ids worth
# extracting, as name=regex pairs separated by ';', each regex with one group:
#   JIRA_ID_PATTERNS='order=Order\s*#?(\d+);customer=Customer\s*id\s*[:=]?\s*(\d+)'
# Without it, identifiers is {}. Never configure patterns for personal data.
#
# Requires: curl, python3 (or python).
set -euo pipefail

ARG="${1:?Usage: fetch_issue.sh <issueKeyOrUrlOrNumber>}"

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

BASE="$JIRA_BASE_URL"
AUTH="$JIRA_EMAIL:$JIRA_API_TOKEN"

# --- Normalize the issue key ------------------------------------------------
KEY="$ARG"
KEY="${KEY##*/browse/}"
KEY="${KEY%%\?*}"
if [[ "$KEY" =~ ^[0-9]+$ ]]; then
  if [[ -z "${JIRA_DEFAULT_PROJECT:-}" ]]; then
    echo "ERROR: '$ARG' is a bare number. Pass the full key (PROJ-$ARG) or set JIRA_DEFAULT_PROJECT." >&2
    exit 1
  fi
  KEY="$JIRA_DEFAULT_PROJECT-$KEY"
fi
KEY="$(printf '%s' "$KEY" | tr '[:lower:]' '[:upper:]')"
if [[ ! "$KEY" =~ ^[A-Z][A-Z0-9_]+-[0-9]+$ ]]; then
  echo "ERROR: '$ARG' is not a valid Jira issue key (expected e.g. PROJ-1234)" >&2
  exit 1
fi

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

fetch_issue() {   # $1 = key ; prints raw JSON, empty on failure
  curl -sf -u "$AUTH" -H "Accept: application/json" \
    "$BASE/rest/api/2/issue/$1" 2>/dev/null || true
}

main_json="$(fetch_issue "$KEY")"
if [[ -z "$main_json" ]]; then
  echo "ERROR: could not read $KEY from $BASE." >&2
  echo "  - check the key exists: $BASE/browse/$KEY" >&2
  echo "  - check JIRA_EMAIL / JIRA_API_TOKEN (with curl -sf a 401 looks like a 404)" >&2
  exit 1
fi

# --- Linked issues (an escalated twin often holds the original report) -------
link_keys="$(printf '%s' "$main_json" | "$PY" -c "
import sys, json
d = json.load(sys.stdin)
out = []
for l in (d.get('fields') or {}).get('issuelinks') or []:
    other = l.get('outwardIssue') or l.get('inwardIssue') or {}
    if other.get('key'):
        out.append(other['key'])
print(' '.join(out))
" | tr -d '\r')"
# tr -d '\r': python prints CRLF on Windows, and a trailing \r breaks the next URL.

linked_dir="$(mktemp -d)"
trap 'rm -rf "$linked_dir"' EXIT
for lk in $link_keys; do
  lj="$(fetch_issue "$lk")"
  [[ -n "$lj" ]] && printf '%s' "$lj" > "$linked_dir/$lk.json"
done

# --- Emit the consolidated, cleaned JSON ------------------------------------
printf '%s' "$main_json" | JIRA_KEY="$KEY" JIRA_BASE="$BASE" LINKED_DIR="$linked_dir" \
  ID_PATTERNS="${JIRA_ID_PATTERNS:-}" "$PY" -c "
import sys, json, os, re, glob

# Service-desk descriptions are often pasted emails: tags, image macros, a
# signature and a legal notice around three useful lines. Cut from the first marker.
BOILERPLATE = [
    'CONFIDENCIALIDAD', 'CONFIDENTIALITY', 'PROTECCION DE DATOS', u'PROTECCIÓN DE DATOS',
    'Este mensaje va dirigido', 'Este mensaje y sus archivos', 'El responsable del tratamiento',
    'This message is intended', 'This e-mail and any attachments',
    'safelinks.protection.outlook.com',
]

def clean(text):
    if not text:
        return ''
    s = text.replace('\r\n', '\n')
    cut = len(s)
    for marker in BOILERPLATE:
        i = s.find(marker)
        if i != -1:
            cut = min(cut, i)
    trimmed = cut < len(s)
    s = s[:cut]
    s = re.sub(r'\{color[^}]*\}', '', s)
    s = re.sub(r'!([^!|\n]+?)(\|[^!\n]*)?!', r'[imagen: \1]', s)
    s = re.sub(r'\[([^\]|\n]*)\|(https?://[^\]\n]+)\]', r'\1 (\2)', s)
    s = re.sub(r'\[([^\]|\n]*)\|mailto:[^\]\n]+\]', r'\1', s)
    s = re.sub(r'\[(mailto:[^\]\n]+)\]', '', s)
    s = re.sub(r'^\s*\*+\s*$', '', s, flags=re.M)
    s = re.sub(r'\{\{(.*?)\}\}', r'\1', s, flags=re.S)
    s = re.sub(r'<(tel|mailto):[^>]*>', '', s)
    s = s.replace(u'​', '')
    s = re.sub(r'^\s*(\[\])+\s*', '', s)
    s = re.sub(r'[ \t]+$', '', s, flags=re.M)
    s = re.sub(r'\n{3,}', '\n\n', s).strip()
    if trimmed:
        s += '\n\n[...firma y aviso legal recortados...]'
    return s

def parse_patterns(raw):
    out = {}
    for chunk in (raw or '').split(';'):
        if '=' not in chunk:
            continue
        name, pat = chunk.split('=', 1)
        name, pat = name.strip(), pat.strip()
        if not name or not pat:
            continue
        try:
            out[name] = re.compile(pat, re.I)
        except re.error as exc:
            sys.stderr.write('WARN: ignoring JIRA_ID_PATTERNS entry %r: %s\n' % (name, exc))
    return out

def identifiers(blobs, patterns):
    joined = '\n'.join(blobs)
    out = {}
    for name, rx in patterns.items():
        vals = sorted(set(m if isinstance(m, str) else m[0] for m in rx.findall(joined)))
        if vals:
            out[name] = vals
    return out

d = json.load(sys.stdin)
f = d.get('fields') or {}
key = os.environ['JIRA_KEY']
base = os.environ['JIRA_BASE']
desc = clean(f.get('description'))

comments = []
for c in ((f.get('comment') or {}).get('comments') or []):
    body = clean(c.get('body'))
    if body:
        comments.append({'created': (c.get('created') or '')[:10], 'body': body})

rel_by_key = {}
for l in f.get('issuelinks') or []:
    other = l.get('outwardIssue') or l.get('inwardIssue') or {}
    if other.get('key'):
        rel_by_key[other['key']] = ((l.get('type') or {}).get('name')) or ''

linked = []
for path in sorted(glob.glob(os.path.join(os.environ['LINKED_DIR'], '*.json'))):
    try:
        with open(path, encoding='utf-8') as fh:
            lj = json.load(fh)
    except Exception:
        continue
    lf = lj.get('fields') or {}
    lkey = lj.get('key', '')
    ldesc = clean(lf.get('description'))
    if ldesc and ldesc == desc:
        ldesc = '(identica a la descripcion del ticket principal)'
    linked.append({
        'key': lkey,
        'url': base + '/browse/' + lkey,
        'relation': rel_by_key.get(lkey, ''),
        'type': ((lf.get('issuetype') or {}).get('name')) or '',
        'status': ((lf.get('status') or {}).get('name')) or '',
        'summary': lf.get('summary', ''),
        'description': ldesc,
    })

attachments = [{
    'filename': a.get('filename', ''),
    'mimeType': a.get('mimeType', ''),
    'size': a.get('size', 0),
} for a in (f.get('attachment') or [])]

blobs = [desc] + [c['body'] for c in comments] + [l['description'] for l in linked]

print(json.dumps({
    'key': key,
    'url': base + '/browse/' + key,
    'type': ((f.get('issuetype') or {}).get('name')) or '',
    'status': ((f.get('status') or {}).get('name')) or '',
    'priority': ((f.get('priority') or {}).get('name')) or '',
    'created': (f.get('created') or '')[:10],
    'summary': f.get('summary', ''),
    'labels': f.get('labels') or [],
    'components': [c.get('name') for c in (f.get('components') or [])],
    'description': desc,
    'identifiers': identifiers(blobs, parse_patterns(os.environ.get('ID_PATTERNS'))),
    'comments': comments,
    'linkedIssues': linked,
    'attachments': attachments,
    'subtasks': [s.get('key') for s in (f.get('subtasks') or [])],
    'parent': ((f.get('parent') or {}).get('key')) or '',
}, ensure_ascii=False, indent=2))
"
