#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

REPO="${THX_CCTV_ISSUE_REPO:-haloshin/bird-feeder-image-generator}"
REMOTE_HOST="${THX_CCTV_REMOTE_HOST:-root@8.135.42.221}"
REMOTE_RUNS_DIR="${THX_CCTV_REMOTE_RUNS_DIR:-/var/www/html/thx-workbuddy/cctv-image-gen/runs}"
PUBLIC_RUNS_BASE="${THX_CCTV_PUBLIC_RUNS_BASE:-http://8.135.42.221/thx-workbuddy/cctv-image-gen/runs}"

ISSUE=""
RUN_DIR=""
FEEDBACK=""
STATUS=""
RESULT=""
GBRAIN_CANDIDATE="待判断"
SUGGESTED_ACTION="继续根据反馈判断。"
FINAL_IMAGE=""
IMAGES=()

usage() {
  printf '%s\n' "Usage: $0 --issue 1 --run-dir /path/to/run --feedback 文本 [--status 可用|需返修|废弃|待判断] [--final-image 图片] [--image 图片]"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --repo) REPO="$2"; shift 2 ;;
    --issue) ISSUE="$2"; shift 2 ;;
    --run-dir) RUN_DIR="$2"; shift 2 ;;
    --feedback) FEEDBACK="$2"; shift 2 ;;
    --status) STATUS="$2"; shift 2 ;;
    --result) RESULT="$2"; shift 2 ;;
    --gbrain-candidate) GBRAIN_CANDIDATE="$2"; shift 2 ;;
    --suggested-action) SUGGESTED_ACTION="$2"; shift 2 ;;
    --image) IMAGES+=("$2"); shift 2 ;;
    --final-image) FINAL_IMAGE="$2"; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) printf 'Unknown argument: %s\n' "$1" >&2; usage; exit 2 ;;
  esac
done

if [[ -z "$ISSUE" || -z "$RUN_DIR" || -z "$FEEDBACK" ]]; then
  usage >&2
  exit 2
fi

if [[ ! -d "$RUN_DIR" ]]; then
  printf 'Run dir not found: %s\n' "$RUN_DIR" >&2
  exit 2
fi

for image in "${IMAGES[@]+"${IMAGES[@]}"}"; do
  if [[ ! -f "$image" ]]; then
    printf 'Image file not found: %s\n' "$image" >&2
    exit 2
  fi
done

if [[ -n "$FINAL_IMAGE" && ! -f "$FINAL_IMAGE" ]]; then
  printf 'Final image file not found: %s\n' "$FINAL_IMAGE" >&2
  exit 2
fi

DATE_SLUG="$(basename "$(dirname "$RUN_DIR")")"
RUN_ID="$(basename "$RUN_DIR")"
ASSET_DIR="$RUN_DIR/assets"
mkdir -p "$ASSET_DIR"

IMAGE_LINKS=""
STAMP="$(date +%H%M%S)"
IMAGE_INDEX=1
for image in "${IMAGES[@]+"${IMAGES[@]}"}"; do
  ext="${image##*.}"
  target="feedback-${STAMP}-$(printf '%02d' "$IMAGE_INDEX").${ext}"
  cp "$image" "$ASSET_DIR/$target"
  IMAGE_LINKS+=$'\n'"![反馈图 ${IMAGE_INDEX}](${PUBLIC_RUNS_BASE}/${DATE_SLUG}/${RUN_ID}/assets/${target})"
  IMAGE_INDEX=$((IMAGE_INDEX + 1))
done

if [[ -n "$FINAL_IMAGE" ]]; then
  ext="${FINAL_IMAGE##*.}"
  target="final-${STAMP}.${ext}"
  cp "$FINAL_IMAGE" "$ASSET_DIR/$target"
  IMAGE_LINKS+=$'\n\n'"**最终可用图**"$'\n\n'"![最终可用图](${PUBLIC_RUNS_BASE}/${DATE_SLUG}/${RUN_ID}/assets/${target})"
fi

COMMENT_FILE="$RUN_DIR/feedback-${STAMP}.md"
{
  printf '## 反馈更新｜%s\n\n' "$(date '+%F %T')"
  printf '**当前状态**：%s\n\n' "${STATUS:-未变更}"
  printf '**结果判断**：%s\n\n' "${RESULT:-未变更}"
  printf '**反馈内容**：\n\n%s\n\n' "$FEEDBACK"
  if [[ -n "$IMAGE_LINKS" ]]; then
    printf '**新增图片**：\n%s\n\n' "$IMAGE_LINKS"
  fi
  printf '**是否需要进入 GBrain**：%s\n\n' "$GBRAIN_CANDIDATE"
  printf '**建议处理**：%s\n' "$SUGGESTED_ACTION"
} > "$COMMENT_FILE"

ssh -o BatchMode=yes -o ConnectTimeout=8 "$REMOTE_HOST" "mkdir -p '$REMOTE_RUNS_DIR/$DATE_SLUG/$RUN_ID'"
rsync -az --delete "$RUN_DIR/" "$REMOTE_HOST:$REMOTE_RUNS_DIR/$DATE_SLUG/$RUN_ID/"

gh issue comment "$ISSUE" --repo "$REPO" --body-file "$COMMENT_FILE" >/dev/null

if [[ -n "$STATUS" ]]; then
  gh label create "status:$STATUS" --repo "$REPO" --color "C5DEF5" --description "THX CCTV image task status" >/dev/null 2>&1 || true
  gh issue edit "$ISSUE" --repo "$REPO" --remove-label "status:待判断" >/dev/null 2>&1 || true
  gh issue edit "$ISSUE" --repo "$REPO" --remove-label "status:需返修" >/dev/null 2>&1 || true
  gh issue edit "$ISSUE" --repo "$REPO" --remove-label "status:可用" >/dev/null 2>&1 || true
  gh issue edit "$ISSUE" --repo "$REPO" --remove-label "status:废弃" >/dev/null 2>&1 || true
  gh issue edit "$ISSUE" --repo "$REPO" --add-label "status:$STATUS" >/dev/null
fi

if [[ "$GBRAIN_CANDIDATE" == "是"* ]]; then
  gh issue edit "$ISSUE" --repo "$REPO" --add-label "gbrain-candidate" >/dev/null
fi

if [[ "$STATUS" == "可用" || "$RESULT" == "可用" ]]; then
  gh issue close "$ISSUE" --repo "$REPO" --comment "已标记为可用图，任务闭环。" >/dev/null
fi

printf 'Updated issue: https://github.com/%s/issues/%s\n' "$REPO" "$ISSUE"
