#!/usr/bin/env bash
set -euo pipefail

# ═══════════════════════════════════════════════════════════════════════
# ByteLyst Investment Trading - Deployment Status Report
# ═══════════════════════════════════════════════════════════════════════
# Usage: ./deployment-status.sh
#
# What it does:
#   1. Shows Docker container status
#   2. Shows deployed commit hashes from devops endpoint
#   3. Shows git log of recent commits
#   4. Shows health endpoint status
#   5. Shows recent deployment history
#   6. Provides suggested actions
# ═══════════════════════════════════════════════════════════════════════

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

log()  { echo -e "${CYAN}[$(date +%H:%M:%S)]${NC} $*"; }
ok()   { echo -e "${GREEN}[$(date +%H:%M:%S)] ✓${NC} $*"; }
warn() { echo -e "${YELLOW}[$(date +%H:%M:%S)] ⚠${NC} $*"; }
fail() { echo -e "${RED}[$(date +%H:%M:%S)] ✗${NC} $*"; }
info() { echo -e "${BLUE}[$(date +%H:%M:%S)] ℹ${NC} $*"; }

# ── Configuration ────────────────────────────────────────────────────
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_DIR="${SCRIPT_DIR}/../learning_ai_invt_trdg"
BACKEND_URL="http://localhost:4025"
WEB_URL="http://localhost:3085"
API_ENDPOINT="https://api.bytelyst.com/invttrdg"
WEB_ENDPOINT="https://invttrdg.bytelyst.com"

# ── Header ─────────────────────────────────────────────────────────────
echo ""
echo -e "${CYAN}╔═══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║${NC}  ByteLyst Investment Trading - Deployment Status Report  ${CYAN}║${NC}"
echo -e "${CYAN}╚═══════════════════════════════════════════════════════════════╝${NC}"
echo ""
info "Report generated at: $(date)"
echo ""

# ── Docker Container Status ─────────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
log "DOCKER CONTAINER STATUS"
log "══════════════════════════════════════════════════════════════════════"
echo ""

BACKEND_CONTAINER="invttrdg-backend"
WEB_CONTAINER="invttrdg-web"

# Check if containers exist
BACKEND_EXISTS=false
WEB_EXISTS=false

if docker ps -a --format '{{.Names}}' | grep -q "^${BACKEND_CONTAINER}$"; then
  BACKEND_EXISTS=true
fi

if docker ps -a --format '{{.Names}}' | grep -q "^${WEB_CONTAINER}$"; then
  WEB_EXISTS=true
fi

if [ "$BACKEND_EXISTS" = false ] && [ "$WEB_EXISTS" = false ]; then
  fail "No containers found. Deployment may not be complete."
  echo ""
else
  # Backend container status
  if [ "$BACKEND_EXISTS" = true ]; then
    BACKEND_STATUS=$(docker inspect --format='{{.State.Status}}' "$BACKEND_CONTAINER" 2>/dev/null || echo "unknown")
    BACKEND_RUNNING=$(docker inspect --format='{{.State.Running}}' "$BACKEND_CONTAINER" 2>/dev/null || echo "false")
    BACKEND_CREATED=$(docker inspect --format='{{.Created}}' "$BACKEND_CONTAINER" 2>/dev/null || echo "unknown")

    if [ "$BACKEND_RUNNING" = "true" ]; then
      ok "Backend container: $BACKEND_CONTAINER"
      info "  Status: Running"
      info "  Created: $BACKEND_CREATED"
    else
      warn "Backend container: $BACKEND_CONTAINER"
      info "  Status: $BACKEND_STATUS (not running)"
      info "  Created: $BACKEND_CREATED"
    fi
  else
    warn "Backend container not found: $BACKEND_CONTAINER"
  fi
  echo ""

  # Web container status
  if [ "$WEB_EXISTS" = true ]; then
    WEB_STATUS=$(docker inspect --format='{{.State.Status}}' "$WEB_CONTAINER" 2>/dev/null || echo "unknown")
    WEB_RUNNING=$(docker inspect --format='{{.State.Running}}' "$WEB_CONTAINER" 2>/dev/null || echo "false")
    WEB_CREATED=$(docker inspect --format='{{.Created}}' "$WEB_CONTAINER" 2>/dev/null || echo "unknown")

    if [ "$WEB_RUNNING" = "true" ]; then
      ok "Web container: $WEB_CONTAINER"
      info "  Status: Running"
      info "  Created: $WEB_CREATED"
    else
      warn "Web container: $WEB_CONTAINER"
      info "  Status: $WEB_STATUS (not running)"
      info "  Created: $WEB_CREATED"
    fi
  else
    warn "Web container not found: $WEB_CONTAINER"
  fi
  echo ""
fi

# ── Deployed Commit Information ──────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
log "DEPLOYED COMMIT INFORMATION"
log "══════════════════════════════════════════════════════════════════════"
echo ""

if [ "$BACKEND_EXISTS" = true ] && [ "$BACKEND_RUNNING" = "true" ]; then
  DEVOPS_RESPONSE=$(curl -s "$BACKEND_URL/api/devops/version" 2>/dev/null || echo "{}")

  if [ "$DEVOPS_RESPONSE" != "{}" ] && [ -n "$DEVOPS_RESPONSE" ]; then
    if command -v jq &> /dev/null; then
      DEPLOYED_COMMIT_SHA=$(echo "$DEVOPS_RESPONSE" | jq -r '.commitSha // empty')
      DEPLOYED_COMMIT_SHA_FULL=$(echo "$DEVOPS_RESPONSE" | jq -r '.commitShaFull // empty')
      DEPLOYED_BRANCH=$(echo "$DEVOPS_RESPONSE" | jq -r '.branch // empty')
      DEPLOYED_BUILT_AT=$(echo "$DEVOPS_RESPONSE" | jq -r '.builtAt // empty')
      DEPLOYED_AUTHOR=$(echo "$DEVOPS_RESPONSE" | jq -r '.commitAuthor // empty')
      DEPLOYED_MESSAGE=$(echo "$DEVOPS_RESPONSE" | jq -r '.commitMessage // empty')
      DEPLOYED_IMAGE=$(echo "$DEVOPS_RESPONSE" | jq -r '.dockerImage // empty')

      ok "Backend deployment info:"
      info "  Commit SHA: ${DEPLOYED_COMMIT_SHA}"
      info "  Commit SHA (full): ${DEPLOYED_COMMIT_SHA_FULL}"
      info "  Branch: ${DEPLOYED_BRANCH}"
      info "  Built at: ${DEPLOYED_BUILT_AT}"
      info "  Author: ${DEPLOYED_AUTHOR}"
      info "  Message: ${DEPLOYED_MESSAGE}"
      info "  Docker image: ${DEPLOYED_IMAGE}"
    else
      warn "jq not installed, showing raw response:"
      echo "$DEVOPS_RESPONSE"
    fi
  else
    warn "Could not retrieve deployment info from devops endpoint"
  fi
else
  warn "Backend container not running, cannot retrieve deployment info"
fi
echo ""

# ── Git Repository Status ───────────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
log "GIT REPOSITORY STATUS"
log "══════════════════════════════════════════════════════════════════════"
echo ""

if [ -d "$REPO_DIR" ]; then
  cd "$REPO_DIR"

  # Current branch
  CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
  info "Current branch: $CURRENT_BRANCH"

  # Latest commit
  LATEST_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")
  LATEST_AUTHOR=$(git log -1 --pretty=format:'%an' 2>/dev/null || echo "unknown")
  LATEST_MESSAGE=$(git log -1 --pretty=format:'%s' 2>/dev/null | head -c 200 || echo "unknown")
  LATEST_DATE=$(git log -1 --pretty=format:'%ai' 2>/dev/null || echo "unknown")

  info "Latest commit: $LATEST_COMMIT"
  info "  Author: $LATEST_AUTHOR"
  info "  Date: $LATEST_DATE"
  info "  Message: $LATEST_MESSAGE"
  echo ""

  # Compare deployed vs latest
  if [ -n "${DEPLOYED_COMMIT_SHA:-}" ] && [ "$DEPLOYED_COMMIT_SHA" != "unknown" ]; then
    if [ "$DEPLOYED_COMMIT_SHA" = "$LATEST_COMMIT" ]; then
      ok "Deployed commit matches latest commit in repository"
    else
      warn "Deployed commit ($DEPLOYED_COMMIT_SHA) differs from latest commit ($LATEST_COMMIT)"
      info "  Consider running deployment script to update"
    fi
  fi
  echo ""

  # Recent commits
  log "Recent commits (last 5):"
  git log --oneline -5 2>/dev/null || warn "Could not retrieve commit history"
  echo ""

  # Uncommitted changes
  if ! git diff-index --quiet HEAD -- 2>/dev/null; then
    warn "Uncommitted changes detected"
    git diff --stat 2>/dev/null || true
  else
    ok "No uncommitted changes"
  fi
  echo ""

  # Unpushed commits
  LOCAL_COMMIT=$(git rev-parse @ 2>/dev/null || echo "")
  REMOTE_COMMIT=$(git rev-parse '@{u}' 2>/dev/null || echo "")

  if [ -n "$REMOTE_COMMIT" ] && [ "$LOCAL_COMMIT" != "$REMOTE_COMMIT" ]; then
    warn "Unpushed commits detected"
    info "  Local: $LOCAL_COMMIT"
    info "  Remote: $REMOTE_COMMIT"
  else
    ok "All commits are pushed"
  fi
else
  warn "Repository directory not found: $REPO_DIR"
fi
echo ""

# ── Health Endpoint Status ───────────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
log "HEALTH ENDPOINT STATUS"
log "══════════════════════════════════════════════════════════════════════"
echo ""

# Backend health
if curl -sf "$BACKEND_URL/health/live" > /dev/null 2>&1; then
  ok "Backend health endpoint: $BACKEND_URL/health/live"
  HEALTH_RESPONSE=$(curl -s "$BACKEND_URL/health/live" 2>/dev/null || echo "{}")
  if command -v jq &> /dev/null; then
    echo "$HEALTH_RESPONSE" | jq '.' 2>/dev/null || echo "$HEALTH_RESPONSE"
  else
    echo "$HEALTH_RESPONSE"
  fi
else
  fail "Backend health endpoint not responding: $BACKEND_URL/health/live"
fi
echo ""

# Web health
if curl -sf "$WEB_URL" > /dev/null 2>&1; then
  ok "Web frontend: $WEB_URL"
  CONTENT_TYPE=$(curl -sI "$WEB_URL" | grep -i content-type || echo "")
  if echo "$CONTENT_TYPE" | grep -qi "text/html"; then
    info "  Content type: HTML"
  else
    warn "  Content type: $CONTENT_TYPE"
  fi
else
  fail "Web frontend not responding: $WEB_URL"
fi
echo ""

# Production endpoints
log "Production endpoints:"
if curl -sf "$API_ENDPOINT/health/live" > /dev/null 2>&1; then
  ok "  API endpoint: $API_ENDPOINT"
else
  warn "  API endpoint not accessible: $API_ENDPOINT"
fi

if curl -sf "$WEB_ENDPOINT" > /dev/null 2>&1; then
  ok "  Web endpoint: $WEB_ENDPOINT"
else
  warn "  Web endpoint not accessible: $WEB_ENDPOINT"
fi
echo ""

# ── Recent Deployment History ───────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
log "RECENT DEPLOYMENT HISTORY"
log "══════════════════════════════════════════════════════════════════════"
echo ""

if [ "$BACKEND_EXISTS" = true ] || [ "$WEB_EXISTS" = true ]; then
  info "Container creation times:"
  if [ "$BACKEND_EXISTS" = true ]; then
    BACKEND_CREATED=$(docker inspect --format='{{.Created}}' "$BACKEND_CONTAINER" 2>/dev/null || echo "unknown")
    info "  Backend: $BACKEND_CREATED"
  fi
  if [ "$WEB_EXISTS" = true ]; then
    WEB_CREATED=$(docker inspect --format='{{.Created}}' "$WEB_CONTAINER" 2>/dev/null || echo "unknown")
    info "  Web: $WEB_CREATED"
  fi
else
  info "No containers found, no deployment history available"
fi
echo ""

# ── Suggested Actions ───────────────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
log "SUGGESTED ACTIONS"
log "══════════════════════════════════════════════════════════════════════"
echo ""

ACTIONS=()

if [ "$BACKEND_EXISTS" = false ] || [ "$WEB_EXISTS" = false ]; then
  ACTIONS+=("• Run deployment script: ./deploy-invttrdg.sh")
fi

if [ "$BACKEND_EXISTS" = true ] && [ "$BACKEND_RUNNING" = false ]; then
  ACTIONS+=("• Start backend container: docker start invttrdg-backend")
fi

if [ "$WEB_EXISTS" = true ] && [ "$WEB_RUNNING" = false ]; then
  ACTIONS+=("• Start web container: docker start invttrdg-web")
fi

if [ -n "${DEPLOYED_COMMIT_SHA:-}" ] && [ -n "${LATEST_COMMIT:-}" ] && [ "$DEPLOYED_COMMIT_SHA" != "$LATEST_COMMIT" ]; then
  ACTIONS+=("• Deploy latest commit: ./deploy-invttrdg.sh")
fi

if [ -d "$REPO_DIR" ]; then
  cd "$REPO_DIR"
  if ! git diff-index --quiet HEAD -- 2>/dev/null; then
    ACTIONS+=("• Commit or stash uncommitted changes in $REPO_DIR")
  fi

  LOCAL_COMMIT=$(git rev-parse @ 2>/dev/null || echo "")
  REMOTE_COMMIT=$(git rev-parse '@{u}' 2>/dev/null || echo "")
  if [ -n "$REMOTE_COMMIT" ] && [ "$LOCAL_COMMIT" != "$REMOTE_COMMIT" ]; then
    ACTIONS+=("• Push unpushed commits: cd $REPO_DIR && git push")
  fi
fi

if ! curl -sf "$BACKEND_URL/health/live" > /dev/null 2>&1; then
  ACTIONS+=("• Check backend logs: docker logs invttrdg-backend")
fi

if ! curl -sf "$WEB_URL" > /dev/null 2>&1; then
  ACTIONS+=("• Check web logs: docker logs invttrdg-web")
fi

if [ ${#ACTIONS[@]} -eq 0 ]; then
  ok "No immediate actions required. Deployment appears healthy."
else
  warn "Recommended actions:"
  for action in "${ACTIONS[@]}"; do
    echo "  $action"
  done
fi
echo ""

# ── Footer ──────────────────────────────────────────────────────────────
log "══════════════════════════════════════════════════════════════════════"
ok "Deployment status report completed"
log "══════════════════════════════════════════════════════════════════════"
echo ""
