#!/bin/bash
# Create giglez repository on Gitea and push
# Based on gitea-command-center pattern

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}🛰️ Creating GigLez Repository on Gitea${NC}"
echo "========================================="
echo ""

# Get token from gopass
echo "Retrieving API token from gopass..."
TOKEN=$(gopass show -o gitea/api-tokens/tea-cli 2>/dev/null)
if [ -z "$TOKEN" ]; then
    echo -e "${RED}❌ Token not found in gopass${NC}"
    echo "Please setup gopass token first"
    exit 1
fi

echo -e "${GREEN}✅ Token retrieved${NC}"

# Get username from API
echo "Getting username..."
USER_INFO=$(curl -sk -H "Authorization: token $TOKEN" https://localhost:3030/api/v1/user)
USERNAME=$(echo "$USER_INFO" | jq -r '.login')

if [ -z "$USERNAME" ] || [ "$USERNAME" = "null" ]; then
    echo -e "${RED}❌ Could not get username from API${NC}"
    echo "Is Gitea running on localhost:3030?"
    echo "Response: $USER_INFO"
    exit 1
fi

echo -e "${GREEN}✅ Logged in as: $USERNAME${NC}"
echo ""

# Check if repository exists
echo "Checking if giglez repository exists..."
REPO_CHECK=$(curl -sk -H "Authorization: token $TOKEN" \
    https://localhost:3030/api/v1/repos/$USERNAME/giglez)

if echo "$REPO_CHECK" | jq -e '.id' > /dev/null 2>&1; then
    echo -e "${YELLOW}⚠️  Repository already exists${NC}"
    REPO_EXISTS=true
else
    echo -e "${GREEN}✅ Repository doesn't exist, will create${NC}"
    REPO_EXISTS=false
fi

# Create repository if it doesn't exist
if [ "$REPO_EXISTS" = false ]; then
    echo ""
    echo "Creating giglez repository..."

    CREATE_RESPONSE=$(curl -sk -X POST \
        -H "Authorization: token $TOKEN" \
        -H "Content-Type: application/json" \
        -d '{
            "name": "giglez",
            "description": "IoT RF Device Mapping Platform - Wigle for Sub-GHz Signals",
            "private": false,
            "default_branch": "main"
        }' \
        https://localhost:3030/api/v1/user/repos)

    if echo "$CREATE_RESPONSE" | jq -e '.id' > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Repository created successfully${NC}"
    else
        echo -e "${RED}❌ Failed to create repository${NC}"
        echo "$CREATE_RESPONSE" | jq .
        exit 1
    fi
fi

echo ""
echo -e "${BLUE}📡 Setting up Git remote${NC}"
echo "================================"

# Get Gitea URL (check for Tailscale or local)
GITEA_URL="https://localhost:3030"
REMOTE_URL="${GITEA_URL}/${USERNAME}/giglez.git"

# Check if origin already exists
if git remote get-url origin > /dev/null 2>&1; then
    echo -e "${YELLOW}⚠️  Remote 'origin' already exists${NC}"
    CURRENT_ORIGIN=$(git remote get-url origin)
    echo "   Current: $CURRENT_ORIGIN"
    echo "   New:     $REMOTE_URL"

    read -p "Replace origin? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        git remote remove origin
        git remote add origin "$REMOTE_URL"
        echo -e "${GREEN}✅ Remote 'origin' updated${NC}"
    fi
else
    git remote add origin "$REMOTE_URL"
    echo -e "${GREEN}✅ Remote 'origin' added${NC}"
fi

echo ""
echo -e "${BLUE}🚀 Pushing to Gitea${NC}"
echo "================================"

# Get current branch
CURRENT_BRANCH=$(git branch --show-current)
echo "Current branch: $CURRENT_BRANCH"

# Push
echo "Pushing $CURRENT_BRANCH to origin..."
if git push -u origin "$CURRENT_BRANCH"; then
    echo -e "${GREEN}✅ Successfully pushed to Gitea!${NC}"
else
    echo -e "${RED}❌ Push failed${NC}"
    exit 1
fi

echo ""
echo "========================================="
echo -e "${GREEN}🎉 Repository Setup Complete!${NC}"
echo "========================================="
echo ""
echo "Repository URL: ${GITEA_URL}/${USERNAME}/giglez"
echo "Git Remote:     $REMOTE_URL"
echo "Branch:         $CURRENT_BRANCH"
echo ""
echo "View your repository:"
echo "  ${GITEA_URL}/${USERNAME}/giglez"
echo ""
