#!/usr/bin/env bash
#===============================================================================
# new-project.sh - สร้าง Astro + Payload CMS project ใหม่จาก Astro Starter Template
#
# Usage: ./new-project.sh [project-name] [project-path]
#
# สร้าง Astro project ใหม่โดย:
# 1. คัดลอก astro-starter template
# 2. ติดตั้ง dependencies
# 3. ตั้งค่า environment
#
# 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' # No Color

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

# Get skill directory
SKILL_DIR="$(dirname "$(dirname "$(readlink -f "$0")")")"
TEMPLATE_DIR="$SKILL_DIR/templates/astro-starter"

#-------------------------------------------------------------------------------
# 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") [project-name] [project-path]

สร้าง Astro + Payload CMS project ใหม่จาก Astro Starter Template

Arguments:
  project-name    ชื่อ project (optional)
  project-path    ที่อยู่ project (default: current directory)

Examples:
  $(basename "$0") my-website
  $(basename "$0") my-website /path/to/projects/

EOF
}

#-------------------------------------------------------------------------------
# Pre-flight checks
#-------------------------------------------------------------------------------

check_requirements() {
    log_info "ตรวจสอบความต้องการของระบบ..."

    # Check git
    if ! command -v git &> /dev/null; then
        log_error "git ไม่พบ กรุณาติดตั้ง git ก่อน"
        exit 1
    fi

    # Check node
    if ! command -v node &> /dev/null; then
        log_error "node.js ไม่พบ กรุณาติดตั้ง node.js ก่อน"
        exit 1
    fi

    NODE_VERSION=$(node -v | cut -d'v' -f2 | cut -d'.' -f1)
    if [ "$NODE_VERSION" -lt 20 ]; then
        log_error "node.js version ต้อง >= 20 (ตอนนี้: $(node -v))"
        exit 1
    fi

    # Check npm
    if ! command -v npm &> /dev/null; then
        log_error "npm ไม่พบ กรุณาติดตั้ง npm ก่อน"
        exit 1
    fi

    # Check template exists
    if [ ! -d "$TEMPLATE_DIR" ]; then
        log_error "ไม่พบ Astro Starter Template: $TEMPLATE_DIR"
        exit 1
    fi

    log_success "ความต้องการของระบบผ่าน (git, node $(node -v), npm)"
}

#-------------------------------------------------------------------------------
# Create project directory
#-------------------------------------------------------------------------------

setup_directory() {
    local actual_project_path="$PROJECT_PATH"

    if [ -n "$PROJECT_NAME" ]; then
        actual_project_path="$PROJECT_PATH/$PROJECT_NAME"
    fi

    # Create directory
    mkdir -p "$actual_project_path"

    # Check if directory is empty
    if [ "$(ls -A "$actual_project_path" | wc -l)" -gt 0 ]; then
        log_warning "Directory ไม่ว่าง: $actual_project_path"
        read -p "ดำเนินต่อ? (y/n): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi

    PROJECT_PATH="$actual_project_path"
    log_info "Project path: $PROJECT_PATH"
}

#-------------------------------------------------------------------------------
# Copy template
#-------------------------------------------------------------------------------

copy_template() {
    log_info "คัดลอก Astro Starter Template..."

    # Copy all template files
    cp -r "$TEMPLATE_DIR/"* "$PROJECT_PATH/"
    cp -r "$TEMPLATE_DIR/src/collections/access" "$PROJECT_PATH/src/collections/" 2>/dev/null || true

    # Copy consent API if exists
    if [ -d "$SKILL_DIR/templates/consent/api" ]; then
        mkdir -p "$PROJECT_PATH/src/pages/api"
        cp "$SKILL_DIR/templates/consent/api/"* "$PROJECT_PATH/src/pages/api/" 2>/dev/null || true
    fi

    log_success "คัดลอก template เสร็จสมบูรณ์"
}

#-------------------------------------------------------------------------------
# Copy legal templates
#-------------------------------------------------------------------------------

copy_legal_templates() {
    log_info "คัดลอก PDPA templates..."

    mkdir -p "$PROJECT_PATH/src/content/pages"

    if [ -f "$SKILL_DIR/templates/privacy-policy.md" ]; then
        cp "$SKILL_DIR/templates/privacy-policy.md" "$PROJECT_PATH/src/content/pages/"
    fi

    if [ -f "$SKILL_DIR/templates/terms-of-service.md" ]; then
        cp "$SKILL_DIR/templates/terms-of-service.md" "$PROJECT_PATH/src/content/pages/"
    fi

    log_success "คัดลอก PDPA templates เสร็จสมบูรณ์"
}

#-------------------------------------------------------------------------------
# Install dependencies
#-------------------------------------------------------------------------------

install_dependencies() {
    log_info "ติดตั้ง dependencies..."

    cd "$PROJECT_PATH"
    npm install

    log_success "ติดตั้ง dependencies เสร็จสมบูรณ์"
}

#-------------------------------------------------------------------------------
# Setup environment
#-------------------------------------------------------------------------------

setup_environment() {
    log_info "ตั้งค่า environment..."

    cd "$PROJECT_PATH"

    if [ ! -f ".env" ]; then
        if [ -f ".env.example" ]; then
            cp .env.example .env
            log_success "สร้าง .env จาก .env.example"
            log_warning "กรุณาแก้ไข .env และใส่ DATABASE_URL ที่ถูกต้อง"
        else
            cat > .env << 'EOF'
# Payload CMS
PAYLOAD_SECRET=change-this-secret-key-at-least-32-characters
DATABASE_URL=postgresql://user:password@localhost:5432/mydb

# Server
SERVER_URL=http://localhost:4321
NODE_ENV=development
EOF
            log_success "สร้าง .env เริ่มต้น"
            log_warning "กรุณาแก้ไข .env และใส่ DATABASE_URL ที่ถูกต้อง"
        fi
    else
        log_info ".env มีอยู่แล้ว"
    fi
}

#-------------------------------------------------------------------------------
# Create AI_RULES.md
#-------------------------------------------------------------------------------

create_ai_rules() {
    log_info "สร้าง AI_RULES.md..."

    cd "$PROJECT_PATH"

    cat > AI_RULES.md << 'EOF'
# AI Rules

## Tech Stack Overview

- **Frontend:** Astro เวอร์ชั่นล่าสุด + TypeScript
- **Backend/CMS:** Payload CMS 3.0
- **Database:** PostgreSQL (via Payload)
- **Styling:** Tailwind CSS v4
- **Authentication:** Payload built-in auth with role-based access
- **Image Handling:** Payload Media collection

## File Organization

- **Collections:** Define Payload collections in `src/collections/`
- **Pages:** Use Astro file-based routing in `src/pages/`
- **Components:** Reusable components in `src/components/`
- **Styles:** Global styles in `src/styles/`

## Never Modify These Files

- `src/payload-types.ts` - Auto-generated by Payload
- `src/migrations/` - Database migration files

## Thai-First

- ใช้ Kanit หรือ Noto Sans Thai fonts
- Thai typography CSS
- Thai structured data (LocalBusiness, Organization)
- ภาษาไทยเป็นหลักใน content
EOF

    log_success "สร้าง AI_RULES.md เสร็จสมบูรณ์"
}

#-------------------------------------------------------------------------------
# Initialize git
#-------------------------------------------------------------------------------

init_git() {
    log_info "เริ่มต้น git..."

    cd "$PROJECT_PATH"

    if [ ! -d ".git" ]; then
        git init
        git add .
        git commit -m "Initial commit: Astro + Payload CMS starter"
        log_success "เริ่มต้น git เสร็จสมบูรณ์"
    else
        log_info "git repo มีอยู่แล้ว"
    fi
}

#-------------------------------------------------------------------------------
# Show project structure
#-------------------------------------------------------------------------------

show_structure() {
    log_info "โครงสร้าง project:"
    cd "$PROJECT_PATH"
    echo ""
    find . -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.astro" -o -name "*.mjs" -o -name "*.css" -o -name "*.md" -o -name "package.json" \) 2>/dev/null | grep -v node_modules | sort | head -30
}

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

main() {
    echo "=============================================="
    echo "  Astro + Payload CMS Project Creator"
    echo "  Using Astro Starter Template"
    echo "=============================================="
    echo ""

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

    # Run steps
    check_requirements
    setup_directory
    copy_template
    copy_legal_templates
    install_dependencies
    setup_environment
    create_ai_rules
    init_git
    show_structure

    echo ""
    echo "=============================================="
    log_success "สร้าง Astro + Payload CMS project เสร็จสมบูรณ์!"
    echo "=============================================="
    echo ""
    echo "ขั้นตอนถัดไป:"
    echo "  1. cd $PROJECT_PATH"
    echo "  2. แก้ไข .env (DATABASE_URL, PAYLOAD_SECRET)"
    echo "  3. npm run db:push (สร้าง database tables)"
    echo "  4. npm run generate (สร้าง Payload types)"
    echo "  5. npm run dev"
    echo "  6. เปิด http://localhost:4321/admin สำหรับ Payload admin"
    echo ""
}

main "$@"
