#!/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}"
RUNS_ROOT="${THX_CCTV_RUNS_ROOT:-$SKILL_DIR/runs}"

PRODUCT=""
PLATFORM=""
REQUEST=""
SUMMARY=""
OPERATOR="未填写"
STATUS="待判断"
RESULT="待判断"
GBRAIN_CANDIDATE="待判断"
SUGGESTED_ACTION="等待运营或负责人判断。"
PROMPT_FILE=""
SELF_CHECK_FILE=""
FEEDBACK_FILE=""
RUN_ID=""
DRY_RUN="0"
FINAL_IMAGE=""
IMAGES=()

usage() {
  printf '%s\n' "Usage: $0 --product 产品 --platform 用途 --request 原始需求 --prompt-file 文件 --self-check-file 文件 [--image 图片] [--feedback-file 文件] [--summary 标题] [--final-image 图片] [--dry-run]"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --repo) REPO="$2"; shift 2 ;;
    --product) PRODUCT="$2"; shift 2 ;;
    --platform) PLATFORM="$2"; shift 2 ;;
    --request) REQUEST="$2"; shift 2 ;;
    --summary) SUMMARY="$2"; shift 2 ;;
    --operator) OPERATOR="$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 ;;
    --prompt-file) PROMPT_FILE="$2"; shift 2 ;;
    --self-check-file) SELF_CHECK_FILE="$2"; shift 2 ;;
    --feedback-file) FEEDBACK_FILE="$2"; shift 2 ;;
    --image) IMAGES+=("$2"); shift 2 ;;
    --final-image) FINAL_IMAGE="$2"; shift 2 ;;
    --run-id) RUN_ID="$2"; shift 2 ;;
    --dry-run) DRY_RUN="1"; shift ;;
    -h|--help) usage; exit 0 ;;
    *) printf 'Unknown argument: %s\n' "$1" >&2; usage; exit 2 ;;
  esac
done

if [[ -z "$PRODUCT" || -z "$PLATFORM" || -z "$REQUEST" || -z "$PROMPT_FILE" || -z "$SELF_CHECK_FILE" ]]; then
  usage >&2
  exit 2
fi

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

if [[ ! -f "$SELF_CHECK_FILE" ]]; then
  printf 'Self-check file not found: %s\n' "$SELF_CHECK_FILE" >&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="$(date +%F)"
TIME_SLUG="$(date +%H%M%S)"
SAFE_PRODUCT="$(printf '%s' "$PRODUCT" | tr -cs '[:alnum:]' '-' | sed 's/^-//;s/-$//')"
if [[ -z "$SAFE_PRODUCT" ]]; then
  SAFE_PRODUCT="product"
fi

if [[ -z "$RUN_ID" ]]; then
  RUN_ID="thx-cctv-${DATE_SLUG}-${TIME_SLUG}-${SAFE_PRODUCT}"
fi

if [[ -z "$SUMMARY" ]]; then
  SUMMARY="$REQUEST"
fi

RUN_DIR="$RUNS_ROOT/$DATE_SLUG/$RUN_ID"
ASSET_DIR="$RUN_DIR/assets"
mkdir -p "$ASSET_DIR"

printf '%s\n' "$REQUEST" > "$RUN_DIR/request.md"
cp "$PROMPT_FILE" "$RUN_DIR/prompt.txt"
cp "$SELF_CHECK_FILE" "$RUN_DIR/self-check.md"

if [[ -n "$FEEDBACK_FILE" && -f "$FEEDBACK_FILE" ]]; then
  cp "$FEEDBACK_FILE" "$RUN_DIR/operator-feedback.md"
else
  printf '%s\n' "待运营或负责人补充。" > "$RUN_DIR/operator-feedback.md"
fi

IMAGE_LINKS=""
IMAGE_INDEX=1
for image in "${IMAGES[@]+"${IMAGES[@]}"}"; do
  ext="${image##*.}"
  target="image-$(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##*.}"
  cp "$FINAL_IMAGE" "$ASSET_DIR/final.${ext}"
  IMAGE_LINKS+=$'\n\n'"**最终可用图**"$'\n\n'"![最终可用图](${PUBLIC_RUNS_BASE}/${DATE_SLUG}/${RUN_ID}/assets/final.${ext})"
fi

if [[ -z "$IMAGE_LINKS" ]]; then
  IMAGE_LINKS="本次未提供图片文件。"
fi

PUBLIC_RUN_URL="${PUBLIC_RUNS_BASE}/${DATE_SLUG}/${RUN_ID}/"

export PRODUCT
export PLATFORM
export SUMMARY
export REQUEST
export RUN_ID
export OPERATOR
export STATUS
export RESULT
export RUN_DIR
export PUBLIC_RUN_URL
export IMAGE_LINKS
export PROMPT_FILE_COPY="$RUN_DIR/prompt.txt"
export SELF_CHECK_FILE_COPY="$RUN_DIR/self-check.md"
export FEEDBACK_FILE_COPY="$RUN_DIR/operator-feedback.md"
export GBRAIN_CANDIDATE
export SUGGESTED_ACTION

python3 - "$SKILL_DIR/templates/image-run-issue.md" "$RUN_DIR/issue.md" <<'PY'
from pathlib import Path
import os
import sys

template = Path(sys.argv[1]).read_text()
output = Path(sys.argv[2])

values = {
    "product": os.environ["PRODUCT"],
    "platform": os.environ["PLATFORM"],
    "summary": os.environ["SUMMARY"],
    "request": os.environ["REQUEST"],
    "run_id": os.environ["RUN_ID"],
    "operator": os.environ["OPERATOR"],
    "status": os.environ["STATUS"],
    "result": os.environ["RESULT"],
    "local_run_dir": os.environ["RUN_DIR"],
    "public_run_url": os.environ["PUBLIC_RUN_URL"],
    "image_links": os.environ["IMAGE_LINKS"],
    "prompt": Path(os.environ["PROMPT_FILE_COPY"]).read_text(),
    "self_check": Path(os.environ["SELF_CHECK_FILE_COPY"]).read_text(),
    "operator_feedback": Path(os.environ["FEEDBACK_FILE_COPY"]).read_text(),
    "gbrain_candidate": os.environ["GBRAIN_CANDIDATE"],
    "suggested_action": os.environ["SUGGESTED_ACTION"],
}

for key, value in values.items():
    template = template.replace("{{" + key + "}}", value)

output.write_text(template)
PY

cat > "$RUN_DIR/manifest.json" <<JSON
{
  "run_id": "$RUN_ID",
  "date": "$DATE_SLUG",
  "repo": "$REPO",
  "product": "$PRODUCT",
  "platform": "$PLATFORM",
  "status": "$STATUS",
  "result": "$RESULT",
  "local_run_dir": "$RUN_DIR",
  "public_run_url": "$PUBLIC_RUN_URL"
}
JSON

if [[ "$DRY_RUN" == "1" ]]; then
  printf 'Dry run created: %s\n' "$RUN_DIR"
  printf 'Issue body: %s\n' "$RUN_DIR/issue.md"
  exit 0
fi

if command -v rsync >/dev/null 2>&1; then
  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/"
fi

gh label create "cctv-image-gen" --repo "$REPO" --color "245F8F" --description "THX CCTV image generation task" >/dev/null 2>&1 || true
gh label create "status:待判断" --repo "$REPO" --color "C5DEF5" --description "Waiting for Shin or operator review" >/dev/null 2>&1 || true
gh label create "status:需返修" --repo "$REPO" --color "FBCA04" --description "Needs repair iteration" >/dev/null 2>&1 || true
gh label create "status:可用" --repo "$REPO" --color "0E8A16" --description "Approved usable asset" >/dev/null 2>&1 || true
gh label create "status:废弃" --repo "$REPO" --color "B60205" --description "Rejected or abandoned output" >/dev/null 2>&1 || true
gh label create "gbrain-candidate" --repo "$REPO" --color "5319E7" --description "May contain reusable GBrain knowledge" >/dev/null 2>&1 || true

LABELS="cctv-image-gen,status:待判断"
if [[ "$STATUS" == "需返修" || "$RESULT" == "需返修" ]]; then
  LABELS="cctv-image-gen,status:需返修"
elif [[ "$STATUS" == "可用" || "$RESULT" == "可用" ]]; then
  LABELS="cctv-image-gen,status:可用"
elif [[ "$STATUS" == "废弃" || "$RESULT" == "废弃" ]]; then
  LABELS="cctv-image-gen,status:废弃"
fi

if [[ "$GBRAIN_CANDIDATE" == "是"* ]]; then
  LABELS="${LABELS},gbrain-candidate"
fi

TITLE="[THX-cctv-image-gen][${PRODUCT}][${PLATFORM}] ${SUMMARY}"
ISSUE_URL="$(gh issue create --repo "$REPO" --title "$TITLE" --body-file "$RUN_DIR/issue.md" --label "$LABELS")"
printf '%s\n' "$ISSUE_URL" | tee "$RUN_DIR/issue-url.txt"
