mkdir -p tools
cat > tools/gen_manifest.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

BASE="${GITEA_BASE:-https://git.sunamura-llc.com}"
OWNER="${GITEA_OWNER:-openRepo}"
REPO="${GITEA_REPO:-AI-ART}"
BRANCH="${GITEA_BRANCH:-main}"

OUT="${OUT:-manifest.json}"
TOKEN="${GITEA_TOKEN:-}"

command -v curl >/dev/null 2>&1 || { echo "ERROR: curl not found"; exit 1; }
command -v jq   >/dev/null 2>&1 || { echo "ERROR: jq not found (mac: brew install jq)"; exit 1; }

if [[ -z "$TOKEN" ]]; then
  echo "ERROR: GITEA_TOKEN is empty"
  echo "例: export GITEA_TOKEN='xxxxx'"
  exit 1
fi

API="${BASE}/api/v1"
AUTH_HEADER="Authorization: token ${TOKEN}"

images_json="$(curl -sS -H "$AUTH_HEADER" \
  "${API}/repos/${OWNER}/${REPO}/contents/images" \
  || true)"

images_array="$(echo "$images_json" | jq -c '
  if type=="array" then
    [.[] | select(.type=="file") | {name: .name, path: .path, url: .download_url}]
  else
    []
  end
')"

cat > "$OUT" <<MANIFEST
{
  "repo": "${OWNER}/${REPO}",
  "branch": "${BRANCH}",
  "readme": "${BASE}/${OWNER}/${REPO}/raw/branch/${BRANCH}/README.md",
  "task_template": "${BASE}/${OWNER}/${REPO}/raw/branch/${BRANCH}/prompts/task_template.md",
  "rules": "${BASE}/${OWNER}/${REPO}/raw/branch/${BRANCH}/.cursorrules",
  "images_dir": "${BASE}/${OWNER}/${REPO}/src/branch/${BRANCH}/images",
  "images": ${images_array},
  "notes": [
    "README.md を条件（ポリシー）として読む",
    "prompts/task_template.md を実行指示として扱う"
  ]
}
MANIFEST

echo "✔ generated: ${OUT}"
echo "  images: $(echo "$images_array" | jq 'length') files"
EOF

chmod +x tools/gen_manifest.sh
