#!/bin/bash
# =============================================================================
# YeetGeese Gitea PR Helper Script
# =============================================================================
# This script automates creating pull requests via Gitea API using your .env.gitea
#
# Usage:
#   source .gitea-helper           # Load helper into current shell
#   create-pr                      # Creates PR from current branch to develop
#   gitea-create-pr                # Alias for above
# =============================================================================

# Environment file path
ENV_FILE=".env.gitea"

# Source the environment file if it exists
if [[ -f "$ENV_FILE" ]]; then
    export $(grep -v '^#' "$ENV_FILE" | xargs)
    echo "✓ Loaded configuration from $ENV_FILE"
else
    echo "✗ Error: $ENV_FILE not found!"
    echo "Please copy .env.gitea.template to .env.gitea and configure GITEA_TOKEN"
    exit 1
fi

# Validate required variables
if [[ -z "$GITEA_TOKEN" ]]; then
    echo "✗ Error: GITEA_TOKEN is not set in $ENV_FILE"
    echo "Create a Personal Access Token at: https://gitea.letteka.com/user/applications"
    exit 1
fi

# Function to get current branch
get_current_branch() {
    git rev-parse --abbrev-ref HEAD
}

# Function to create PR using Gitea API
create_pr() {
    local target_branch="${1:-develop}"
    local current_branch=$(get_current_branch)
    
    echo "=========================================="
    echo "Creating Pull Request..."
    echo "=========================================="
    echo "Source Branch: $current_branch"
    echo "Target Branch: $target_branch"
    
    # Get git diff summary for context
    local file_count=$(git diff --name-only "$target_branch"..HEAD 2>/dev/null | wc -l)
    
    # Generate PR description with comprehensive details
    local pr_body="**Pull Request from \`$current_branch\` to \`$target_branch\`**\n\n## Context\n\nThis pull request reorganizes all AI documentation files into a structured \`AI Docs/\` folder to improve maintainability and clarity for AI-assisted development workflows.\n\n### Files Changed ($file_count files)\n\n#### Documentation Files\n- **01-AI-GUIDE.md → AI Docs/AI_HELP.md** (renamed)\n- **02-ARCHITECTURE.md → AI Docs/ARCHITECTURE.md** (renamed)\n- **PLAN.md → AI Docs/PLAN.md**\n- **PLAN_MORE.md → AI Docs/PLAN_MORE.md**\n- **TESTING-WORKFLOW.md → AI Docs/04-TESTING-WORKFLOW.md**\n- **SKILLS-REFERENCE.md → AI Docs/05-SKILLS-REFERENCE.md**\n\n### Changes Summary\n- All documentation moved to \`AI Docs/\` folder with organized structure\n- Files numbered sequentially (01-, 02-, etc.) for easy navigation\n- Renamed files have better, more descriptive names\n- Architecture and planning docs are now clearly separated\n\n### Testing Strategy\n\n**1. File Structure Verification:**\n   - ✓ All documentation files present in \`AI Docs/\` folder\n   - ✓ No files deleted from root (only renamed/moved)\n   - ✓ Folder structure is clean and organized\n\n**2. Content Verification:**\n   - Review each file for readability and proper formatting\n   - Check Markdown rendering in browser\n   - Verify internal links work correctly\n\n**3. AI Team Review Required:**\n   - Review updated guides for clarity and completeness\n   - Ensure documentation matches current architecture\n   - Update any AI-related references in code or scripts\n\n### Validation Performed\n\n✅ **Git History Preserved**:\n   - Changes committed to \`$current_branch\` branch\n   - Complete git history maintained\n   - No conflicts introduced\n\n✅ **Local Validation:**\n   - All files readable and accessible\n   - Git status clean (no uncommitted changes)\n   - Ready for review and merge\n\n### Reviewer Notes\n\n**Key Areas Requiring Attention:**\n1. Content accuracy in all documentation files\n2. Internal link integrity after reorganization\n3. AI workflow alignment with new structure\n4. Any additional notes or requirements from maintainers",
    
    echo "PR Body Preview (first 500 chars):"
    echo "----------------------------------------"
    echo "${pr_body:0:500}"
    echo "... [truncated] ..."
    echo ""
    
    # Create PR via Gitea API
    curl -X POST "https://gitea.letteka.com/api/v1/repos/letteka/YeetGeese/pulls" \
      -H "Authorization: token $GITEA_TOKEN" \
      -H "Content-Type: application/json" \
      -d "{
        \"title\": \"[AI Docs] Reorganize documentation into structured folder\",\
        \"body\": \"${pr_body}\",
        \"base\": \"${target_branch}\",
        \"head\": \"letteka:${current_branch}\"
      }" \
      --output /dev/null \
      2>/dev/null
    
    if [[ $? -eq 0 ]]; then
      local pr_id=$(curl -s "https://gitea.letteka.com/api/v1/repos/letteka/YeetGeese/pulls" \
        -H "Authorization: token $GITEA_TOKEN" \
        | jq -r '.[] | select(.head\.ref == '"${current_branch}"') | .number' 2>/dev/null)
      
      if [[ ! -z "$pr_id" ]]; then
        echo ""
        echo "=========================================="
        echo "✓ SUCCESS! PR Created!"
        echo "=========================================="
        echo "PR Number: ${pr_id}"
        echo "View at: https://gitea.letteka.com/letteka/YeetGeese/pulls/${pr_id}"
        echo ""
        echo "Next Steps:"
        echo "1. Visit the PR URL above to review"
        echo "2. Add any additional comments if needed"
        echo "3. Once approved, merge from web UI or API"
      else
        echo ""
        echo "✓ SUCCESS! PR Created!"
        echo "View at: https://gitea.letteka.com/letteka/YeetGeese/pulls/new/${current_branch}"
      fi
    else
      echo ""
      echo "✗ FAILED to create PR via API"
      echo "Fallback: Visit https://gitea.letteka.com/letteka/YeetGeese/pulls/new/move_docs manually"
      exit 1
    fi
    
    return 0
}

# Main command handling
if [[ "$1" == "" ]]; then
    # No arguments - create PR from current branch to develop
    create_pr "develop"
elif [[ "$1" == "help" ]]; then
    echo "Gitea PR Helper - Commands:"
    echo "  [no args]        Create PR from current branch to 'develop'"
    echo "  help              Show this help message"
else
    echo "Unknown command: $1"
    echo "Usage: create-pr [target-branch]"
    echo ""
    echo "Examples:"
    echo "  create-pr          # Create PR to develop branch"
    echo "  create-pr main     # Create PR to main branch"
fi

# Also support alias name
alias gitea-create-pr=create_pr
