#!/usr/bin/env bash
#===============================================================================
# convert-astro.sh - แปลงเว็บเก่าเป็น Astro + Payload CMS
#
# Usage: ./convert-astro.sh [source-path] [project-name]
#
# รองรับ:
# - Astro เวอร์ชั่นเก่า
# - Next.js
# - Static HTML
#
# Requirements:
# - git
# - node.js 20+
# - npm
#
#===============================================================================

set -e

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

# Default values
SOURCE_PATH="${1:-}"
PROJECT_NAME="${2:-}"

#-------------------------------------------------------------------------------
# Helper functions
#-------------------------------------------------------------------------------

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_usage() {
    cat << EOF
Usage: $(basename "$0") [source-path] [project-name]

แปลงเว็บเก่าเป็น Astro + Payload CMS

Arguments:
  source-path      ที่อยู่เว็บเก่า
  project-name     ชื่อ project ใหม่

Supported Sources:
  - Astro เวอร์ชั่นเก่า
  - Next.js
  - Static HTML

Examples:
  $(basename "$0") /path/to/old-site my-new-site

EOF
}

#-------------------------------------------------------------------------------
# Detect source type
#-------------------------------------------------------------------------------

detect_source_type() {
    log_info "ตรวจสอบประเภทเว็บเก่า..."

    if [ ! -d "$SOURCE_PATH" ]; then
        log_error "ไม่พบ source path: $SOURCE_PATH"
        exit 1
    fi

    cd "$SOURCE_PATH"

    if [ -f "package.json" ]; then
        if grep -q '"next"' "package.json" 2>/dev/null; then
            SOURCE_TYPE="nextjs"
            log_success "ตรวจพบ: Next.js"
        elif grep -q '"astro"' "package.json" 2>/dev/null; then
            SOURCE_TYPE="astro"
            log_success "ตรวจพบ: Astro"
        elif grep -q '"remix"' "package.json" 2>/dev/null; then
            SOURCE_TYPE="remix"
            log_success "ตรวจพบ: Remix"
        elif grep -q '"nuxt"' "package.json" 2>/dev/null; then
            SOURCE_TYPE="nuxt"
            log_success "ตรวจพบ: Nuxt"
        else
            SOURCE_TYPE="unknown"
            log_warning "ไม่สามารถระบุประเภท - จะใช้เป็น static HTML"
        fi
    elif [ -f "index.html" ]; then
        SOURCE_TYPE="static"
        log_success "ตรวจพบ: Static HTML"
    else
        log_error "ไม่พบ package.json หรือ index.html"
        exit 1
    fi
}

#-------------------------------------------------------------------------------
# Backup source
#-------------------------------------------------------------------------------

backup_source() {
    log_info "สำรองข้อมูลเว็บเก่า..."

    BACKUP_DIR="/tmp/backup-$(basename "$SOURCE_PATH")-$(date +%s)"
    mkdir -p "$BACKUP_DIR"

    cp -r "$SOURCE_PATH" "$BACKUP_DIR/"

    log_success "สำรองข้อมูลที่: $BACKUP_DIR"
}

#-------------------------------------------------------------------------------
# Analyze structure
#-------------------------------------------------------------------------------

analyze_structure() {
    log_info "วิเคราะห์โครงสร้างเว็บเก่า..."

    cd "$SOURCE_PATH"

    echo ""
    echo "  โครงสร้างไฟล์:"
    find . -type f \( -name "*.astro" -o -name "*.tsx" -o -name "*.jsx" -o -name "*.vue" -o -name "*.html" -o -name "*.md" -o -name "*.mdx" \) 2>/dev/null | grep -v node_modules | head -30

    echo ""
    echo "  Package.json scripts:"
    if [ -f "package.json" ]; then
        grep -A 10 '"scripts"' "package.json" 2>/dev/null | head -15
    fi
}

#-------------------------------------------------------------------------------
# Create new Astro project
#-------------------------------------------------------------------------------

create_new_project() {
    log_info "สร้าง Astro project ใหม่..."

    NEW_PROJECT_PATH="$(dirname "$SOURCE_PATH")/$PROJECT_NAME"

    if [ -d "$NEW_PROJECT_PATH" ]; then
        log_warning "Project มีอยู่แล้ว: $NEW_PROJECT_PATH"
        read -p "ลบและสร้างใหม่? (y/n): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            rm -rf "$NEW_PROJECT_PATH"
        else
            log_info "ใช้ existing project"
            return 0
        fi
    fi

    mkdir -p "$NEW_PROJECT_PATH"
    cd "$NEW_PROJECT_PATH"

    # Create Astro project
    npm create astro@latest . -- --template minimal --no-install --no-git --typescript strict << EOF
y
EOF

    log_success "สร้าง Astro project เสร็จสมบูรณ์: $NEW_PROJECT_PATH"
}

#-------------------------------------------------------------------------------
# Copy content
#-------------------------------------------------------------------------------

copy_content() {
    log_info "คัดลอก content..."

    cd "$SOURCE_PATH"

    # Copy markdown content
    if [ -d "src/content" ]; then
        mkdir -p "$NEW_PROJECT_PATH/src/content/migration"
        cp -r src/content/* "$NEW_PROJECT_PATH/src/content/migration/"
        log_success "คัดลอก content จาก src/content"
    elif [ -d "content" ]; then
        mkdir -p "$NEW_PROJECT_PATH/src/content/migration"
        cp -r content/* "$NEW_PROJECT_PATH/src/content/migration/"
        log_success "คัดลอก content จาก content"
    fi

    # Copy public assets
    if [ -d "public" ]; then
        cp -r public/* "$NEW_PROJECT_PATH/public/" 2>/dev/null || true
        log_success "คัดลอก public assets"
    fi

    # Copy pages (needs manual conversion)
    if [ -d "src/pages" ] || [ -d "pages" ]; then
        mkdir -p "$NEW_PROJECT_PATH/src/pages/legacy"
        log_info "Pages ต้องการ manual conversion - เก็บไว้ที่ legacy/"
    fi
}

#-------------------------------------------------------------------------------
# Create content migration report
#-------------------------------------------------------------------------------

create_migration_report() {
    log_info "สร้าง migration report..."

    cd "$SOURCE_PATH"

    local page_count=$(find . -type f \( -name "*.astro" -o -name "*.tsx" -o -name "*.jsx" -o -name "*.html" -o -name "*.md" -o -name "*.mdx" \) 2>/dev/null | grep -v node_modules | wc -l)

    cat > "$NEW_PROJECT_PATH/MIGRATION_REPORT.md" << EOF
# Migration Report

## Source Information
- **Type:** $SOURCE_TYPE
- **Path:** $SOURCE_PATH
- **Backup:** $BACKUP_DIR
- **Date:** $(date)

## Content Statistics
- **Total Pages:** $page_count

## Files to Migrate

### Pages (Manual Conversion Required)
EOF

    # List pages that need conversion
    if [ -d "src/pages" ]; then
        find src/pages -type f \( -name "*.astro" -o -name "*.tsx" -o -name "*.jsx" \) 2>/dev/null >> "$NEW_PROJECT_PATH/MIGRATION_REPORT.md"
    elif [ -d "pages" ]; then
        find pages -type f \( -name "*.html" -o -name "*.jsx" -o -name "*.tsx" \) 2>/dev/null >> "$NEW_PROJECT_PATH/MIGRATION_REPORT.md"
    fi

    cat >> "$NEW_PROJECT_PATH/MIGRATION_REPORT.md" << EOF

### Content (Auto-migrated)
EOF

    if [ -d "$NEW_PROJECT_PATH/src/content/migration" ]; then
        find "$NEW_PROJECT_PATH/src/content/migration" -type f -name "*.md" -o -name "*.mdx" 2>/dev/null >> "$NEW_PROJECT_PATH/MIGRATION_REPORT.md"
    fi

    log_success "สร้าง migration report: $NEW_PROJECT_PATH/MIGRATION_REPORT.md"
}

#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------

main() {
    echo "=============================================="
    echo "  Website Migration Tool"
    echo "  แปลงเว็บเก่าเป็น Astro + Payload CMS"
    echo "=============================================="
    echo ""

    if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
        print_usage
        exit 0
    fi

    if [ -z "$SOURCE_PATH" ]; then
        print_usage
        echo ""
        log_error "กรุณาระบุ source path"
        exit 1
    fi

    detect_source_type
    backup_source
    analyze_structure
    create_new_project
    copy_content
    create_migration_report

    echo ""
    echo "=============================================="
    log_success "Migration เริ่มต้นเสร็จสมบูรณ์!"
    echo "=============================================="
    echo ""
    echo "ขั้นตอนถัดไป:"
    echo "  1. cd $NEW_PROJECT_PATH"
    echo "  2. npm install"
    echo "  3. ดู MIGRATION_REPORT.md"
    echo "  4. ปรับ content และ pages ตาม report"
    echo "  5. npm run dev"
    echo ""
}

main "$@"
