#!/bin/bash
# Development Helper Script for BinectChrome
# Quick commands for common development tasks

set -e

EXTENSION_NAME="BinectChrome"
DIST_DIR="./dist"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Print colored message
print_msg() {
    local color=$1
    local msg=$2
    echo -e "${color}${msg}${NC}"
}

# Show usage
usage() {
    echo "BinectChrome Development Helper"
    echo ""
    echo "Usage: ./dev-helper.sh [command]"
    echo ""
    echo "Commands:"
    echo "  build          - Production build"
    echo "  dev            - Start development mode (watch)"
    echo "  clean          - Clean dist directory and rebuild"
    echo "  test           - Run tests"
    echo "  check          - Run type-check and lint"
    echo "  open-chrome    - Open Chrome extension management"
    echo "  open-sw        - Open Chrome service worker internals"
    echo "  verify         - Verify dist build is valid"
    echo "  help           - Show this help"
    echo ""
    echo "Quick Test-Fix Loop:"
    echo "  1. Run: ./dev-helper.sh dev (in one terminal)"
    echo "  2. Make changes in src/"
    echo "  3. Run: ./dev-helper.sh verify"
    echo "  4. Reload extension in Chrome (chrome://extensions/)"
}

# Build production
build() {
    print_msg "$BLUE" "📦 Building extension..."
    npm run build
    print_msg "$GREEN" "✅ Build complete!"
    verify
}

# Start development mode
dev() {
    print_msg "$BLUE" "🔧 Starting development mode (watch)..."
    print_msg "$YELLOW" "Press Ctrl+C to stop"
    print_msg "$YELLOW" "Tip: After changes, reload extension at chrome://extensions/"
    npm run dev
}

# Clean and rebuild
clean() {
    print_msg "$BLUE" "🧹 Cleaning dist directory..."
    rm -rf "$DIST_DIR"
    print_msg "$GREEN" "✅ Cleaned!"
    build
}

# Run tests
test() {
    print_msg "$BLUE" "🧪 Running tests..."
    npm test
}

# Type check and lint
check() {
    print_msg "$BLUE" "🔍 Running type-check..."
    npm run type-check
    print_msg "$BLUE" "🔍 Running lint..."
    npm run lint
    print_msg "$GREEN" "✅ All checks passed!"
}

# Open Chrome extensions page
open_chrome() {
    print_msg "$BLUE" "🌐 Opening Chrome extensions page..."
    if command -v google-chrome &> /dev/null; then
        google-chrome chrome://extensions/ &
    elif command -v chromium &> /dev/null; then
        chromium chrome://extensions/ &
    else
        print_msg "$YELLOW" "⚠️  Chrome not found. Please open chrome://extensions/ manually"
    fi
}

# Open Chrome service worker internals
open_sw() {
    print_msg "$BLUE" "🌐 Opening Chrome service worker internals..."
    if command -v google-chrome &> /dev/null; then
        google-chrome chrome://serviceworker-internals/ &
    elif command -v chromium &> /dev/null; then
        chromium chrome://serviceworker-internals/ &
    else
        print_msg "$YELLOW" "⚠️  Chrome not found. Please open chrome://serviceworker-internals/ manually"
    fi
}

# Verify build
verify() {
    print_msg "$BLUE" "🔍 Verifying build..."

    # Check if dist exists
    if [ ! -d "$DIST_DIR" ]; then
        print_msg "$RED" "❌ dist/ directory not found. Run build first."
        exit 1
    fi

    # Check required files
    REQUIRED_FILES=(
        "$DIST_DIR/manifest.json"
        "$DIST_DIR/background.js"
        "$DIST_DIR/popup.html"
        "$DIST_DIR/popup.js"
    )

    for file in "${REQUIRED_FILES[@]}"; do
        if [ ! -f "$file" ]; then
            print_msg "$RED" "❌ Missing required file: $file"
            exit 1
        fi
    done

    # Check manifest has required permissions
    if ! grep -q '"alarms"' "$DIST_DIR/manifest.json"; then
        print_msg "$RED" "❌ manifest.json missing 'alarms' permission"
        exit 1
    fi

    # Check background.js is an ES module (should start with export/import)
    if ! grep -qE '^(export|import)' "$DIST_DIR/background.js"; then
        print_msg "$YELLOW" "⚠️  background.js might not be a proper ES module"
        print_msg "$YELLOW" "   First line: $(head -n 1 $DIST_DIR/background.js)"
    fi

    print_msg "$GREEN" "✅ Build verification passed!"
    print_msg "$BLUE" "📋 Build info:"
    echo "   - Manifest version: $(grep -o '"version": "[^"]*"' $DIST_DIR/manifest.json | cut -d'"' -f4)"
    echo "   - Background size: $(du -h $DIST_DIR/background.js | cut -f1)"
    echo "   - Popup size: $(du -h $DIST_DIR/popup.js | cut -f1)"
    echo ""
    print_msg "$YELLOW" "Next steps:"
    echo "   1. Go to chrome://extensions/"
    echo "   2. Click 'Load unpacked'"
    echo "   3. Select: $DIST_DIR"
    echo "   4. Or reload if already loaded"
}

# Main
case "${1:-}" in
    build)
        build
        ;;
    dev)
        dev
        ;;
    clean)
        clean
        ;;
    test)
        test
        ;;
    check)
        check
        ;;
    open-chrome)
        open_chrome
        ;;
    open-sw)
        open_sw
        ;;
    verify)
        verify
        ;;
    help|--help|-h)
        usage
        ;;
    *)
        if [ -n "${1:-}" ]; then
            print_msg "$RED" "❌ Unknown command: $1"
            echo ""
        fi
        usage
        exit 1
        ;;
esac
