#!/bin/bash
#
# Script zum Anlegen des Gitea Issues:
# "Placeholder Registry: UNRESOLVED & TO_VERIFY Metadaten prüfen"
#
# Usage: ./create_metadaten_review_issue.sh YOUR_GITEA_TOKEN
#

if [ -z "$1" ]; then
    echo "ERROR: Gitea Token erforderlich"
    echo "Usage: $0 YOUR_GITEA_TOKEN"
    echo ""
    echo "Token erstellen:"
    echo "  1. Gitea öffnen: http://192.168.2.144:3000"
    echo "  2. Settings → Applications → Generate New Token"
    echo "  3. Name: 'Claude Code Issue Management'"
    echo "  4. Scope: issue (read/write)"
    echo "  5. Token kopieren und als Argument übergeben"
    exit 1
fi

GITEA_TOKEN="$1"
GITEA_URL="http://192.168.2.144:3000"
REPO_OWNER="Lars"
REPO_NAME="mitai-jinkendo"

# Issue Body aus Datei lesen (erste 30 Zeilen überspringen = Metadaten)
ISSUE_BODY=$(tail -n +30 .claude/task/rework_0b_placeholder/ISSUE_METADATEN_REVIEW.md)

# JSON Payload erstellen
cat > /tmp/gitea_issue_payload.json << EOF
{
  "title": "Placeholder Registry: UNRESOLVED & TO_VERIFY Metadaten prüfen",
  "body": $(echo "$ISSUE_BODY" | jq -Rs .),
  "labels": [1, 2, 3],
  "priority": 2
}
EOF

echo "Erstelle Gitea Issue..."
echo "Repository: $REPO_OWNER/$REPO_NAME"
echo ""

# Issue via API anlegen
RESPONSE=$(curl -s -X POST \
  "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/issues" \
  -H "Authorization: token $GITEA_TOKEN" \
  -H "Content-Type: application/json" \
  -d @/tmp/gitea_issue_payload.json)

# Response prüfen
if echo "$RESPONSE" | grep -q '"number"'; then
    ISSUE_NUMBER=$(echo "$RESPONSE" | jq -r '.number')
    ISSUE_URL=$(echo "$RESPONSE" | jq -r '.html_url')

    echo "✓ Issue erfolgreich erstellt!"
    echo ""
    echo "Issue #$ISSUE_NUMBER"
    echo "URL: $ISSUE_URL"
    echo ""

    # Labels setzen (falls nicht automatisch gesetzt)
    echo "Setze Labels..."
    curl -s -X POST \
      "$GITEA_URL/api/v1/repos/$REPO_OWNER/$REPO_NAME/issues/$ISSUE_NUMBER/labels" \
      -H "Authorization: token $GITEA_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"labels": [1, 2, 3]}' > /dev/null

    echo "✓ Fertig!"
else
    echo "✗ Fehler beim Erstellen des Issues:"
    echo "$RESPONSE" | jq .
    exit 1
fi

# Cleanup
rm -f /tmp/gitea_issue_payload.json
