#!/usr/bin/env bash
##############################################################
# GMLM Platform — GitHub Repository Push Script
#
# Pushes the complete GMLM codebase to a GitHub repository.
#
# Usage:
#   bash scripts/push-to-github.sh \
#     --token  ghp_XXXXXXXXXXXXXXXXXXXX \
#     --repo   your-org/gmlm-platform \
#     --branch main \
#     [--create-repo]    # Creates the repo if it doesn't exist
#
# Requires: git, curl, jq
##############################################################

set -euo pipefail

GITHUB_TOKEN=""
REPO=""
BRANCH="main"
CREATE_REPO=false
COMMIT_MSG="feat: GMLM Platform v1.0.0 — complete enterprise MLM SaaS build"

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --token)       GITHUB_TOKEN="$2"; shift ;;
        --repo)        REPO="$2";         shift ;;
        --branch)      BRANCH="$2";       shift ;;
        --create-repo) CREATE_REPO=true   ;;
        --message)     COMMIT_MSG="$2";   shift ;;
        *) echo "Unknown: $1"; exit 1 ;;
    esac
    shift
done

if [[ -z "$GITHUB_TOKEN" || -z "$REPO" ]]; then
    echo "Error: --token and --repo are required."
    echo "Usage: bash scripts/push-to-github.sh --token ghp_XXX --repo org/gmlm-platform"
    exit 1
fi

GITHUB_API="https://api.github.com"
REPO_OWNER=$(echo "$REPO" | cut -d'/' -f1)
REPO_NAME=$(echo "$REPO" | cut -d'/' -f2)

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║   GMLM → GitHub Push                     ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  Repository: ${REPO}"
echo "  Branch:     ${BRANCH}"
echo ""

# ── Check if jq is installed ──────────────────────────────────
if ! command -v jq &>/dev/null; then
    apt-get install -y -qq jq 2>/dev/null || brew install jq 2>/dev/null || {
        echo "Error: jq is required. Install with: apt-get install jq"
        exit 1
    }
fi

# ── API helper ────────────────────────────────────────────────
gh_api() {
    curl -sf \
        -H "Authorization: token ${GITHUB_TOKEN}" \
        -H "Accept: application/vnd.github.v3+json" \
        -H "Content-Type: application/json" \
        "$@"
}

# ── Step 1: Verify token and permissions ──────────────────────
echo "▶ Verifying GitHub token..."
USER_JSON=$(gh_api "${GITHUB_API}/user")
USERNAME=$(echo "$USER_JSON" | jq -r '.login')
echo "✓ Authenticated as: ${USERNAME}"

# ── Step 2: Create repository if it doesn't exist ─────────────
REPO_EXISTS=$(gh_api "${GITHUB_API}/repos/${REPO}" 2>/dev/null | jq -r '.full_name // "not_found"')

if [[ "$REPO_EXISTS" == "not_found" ]]; then
    if [[ "$CREATE_REPO" == "true" ]]; then
        echo "▶ Creating repository ${REPO}..."
        gh_api -X POST "${GITHUB_API}/user/repos" \
            -d "{\"name\": \"${REPO_NAME}\", \"private\": true, \"description\": \"GMLM Platform — Enterprise MLM Software\", \"auto_init\": false}" \
            > /dev/null
        echo "✓ Repository created."
        sleep 2
    else
        echo "✗ Repository ${REPO} does not exist."
        echo "  Run with --create-repo to create it automatically."
        exit 1
    fi
else
    echo "✓ Repository found: ${REPO}"
fi

# ── Step 3: Use git to push ────────────────────────────────────
echo "▶ Initializing git repository..."
cd "$(git rev-parse --show-toplevel 2>/dev/null || echo .)"

if [[ ! -d ".git" ]]; then
    git init
    git checkout -b "${BRANCH}" 2>/dev/null || true
fi

# Configure git user if not set
git config user.email "gmlm-deploy@globalmlmsoftware.com" 2>/dev/null || true
git config user.name "GMLM Deploy" 2>/dev/null || true

# ── Step 4: Create/update .gitignore ─────────────────────────
cat > .gitignore << 'GITIGNORE'
/node_modules
/public/hot
/public/storage
/public/build
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.idea
/.vscode
*.swp
*.swo
releases/
.deployment-credentials
storage/logs/*.log
storage/framework/cache/
storage/framework/sessions/
storage/framework/views/
storage/app/backups/
bootstrap/cache/*.php
GITIGNORE

# ── Step 5: Stage all files ───────────────────────────────────
echo "▶ Staging files..."
git add -A
git status --short | head -20
echo "  ($(git diff --cached --numstat | wc -l | tr -d ' ') files staged)"

# ── Step 6: Commit ────────────────────────────────────────────
echo "▶ Creating commit..."
git commit -m "${COMMIT_MSG}" \
    --allow-empty \
    -q

echo "✓ Commit created."

# ── Step 7: Push to GitHub ─────────────────────────────────────
echo "▶ Pushing to GitHub..."
REMOTE_URL="https://${GITHUB_TOKEN}@github.com/${REPO}.git"

# Add remote if not already set
git remote remove origin 2>/dev/null || true
git remote add origin "${REMOTE_URL}"

# Push
git push origin "${BRANCH}" --force-with-lease 2>&1 | grep -v "token" || \
git push origin "${BRANCH}" --force 2>&1 | grep -v "token"

echo "✓ Code pushed to GitHub."

# ── Step 8: Create initial release tag ────────────────────────
VERSION=$(cat config/gmlm.php 2>/dev/null | grep "'version'" | head -1 | grep -oP "'\K[^']+(?=')" || echo "1.0.0")

echo "▶ Creating release tag v${VERSION}..."
gh_api -X POST "${GITHUB_API}/repos/${REPO}/releases" \
    -d "{
        \"tag_name\": \"v${VERSION}\",
        \"name\": \"v${VERSION} — Initial Release\",
        \"body\": \"GMLM Platform v${VERSION} — Enterprise MLM SaaS Platform\\n\\nSee README.md for installation instructions.\",
        \"draft\": false,
        \"prerelease\": false,
        \"target_commitish\": \"${BRANCH}\"
    }" > /dev/null 2>&1 || echo "  (Tag may already exist — skipped)"

# ── Summary ────────────────────────────────────────────────────
echo ""
echo "╔══════════════════════════════════════════╗"
echo "║   ✓ Successfully Pushed to GitHub        ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "  Repository:  https://github.com/${REPO}"
echo "  Branch:      ${BRANCH}"
echo "  Tag:         v${VERSION}"
echo ""
echo "  End users can now deploy with:"
echo "  git clone https://github.com/${REPO}.git"
echo ""
