#!/usr/bin/env bash
#===============================================================================
# audit-seo.sh - SEO Audit สำหรับ Next.js + Payload CMS project
#
# Usage: ./audit-seo.sh [project-path]
#
# ตรวจสอบ SEO ของเว็บไซต์:
# - Meta tags
# - Heading structure
# - Sitemap
# - Robots.txt
# - Open Graph tags
# - JSON-LD structured data
# - Thai language optimization
#
# Requirements:
# - node.js
# - npm
# - curl
#
#===============================================================================

set -e

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

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

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

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

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

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

log_fail() {
    echo -e "${RED}[FAIL]${NC} $1"
}

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

SEO Audit สำหรับ Next.js + Payload CMS project

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

Examples:
  $(basename "$0")
  $(basename "$0") /path/to/project

EOF
}

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

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

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

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

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

    log_success "ความต้องการของระบบผ่าน"
}

#-------------------------------------------------------------------------------
# Check project structure
#-------------------------------------------------------------------------------

check_project_structure() {
    echo ""
    echo "=============================================="
    echo "  1. Project Structure"
    echo "=============================================="

    cd "$PROJECT_PATH"

    if [ ! -f "next.config.ts" ] && [ ! -f "next.config.js" ]; then
        log_fail "ไม่พบ next.config.ts หรือ next.config.js"
    else
        log_success "พบ Next.js config"
    fi

    if [ -d "src/app" ]; then
        local page_count=$(find src/app -name "page.tsx" -o -name "page.ts" | wc -l)
        log_success "พบ $page_count pages"
    else
        log_fail "ไม่พบ src/app"
    fi

    if [ -d "src/components" ]; then
        log_success "พบ components directory"
    else
        log_warning "ไม่พบ components directory"
    fi

    if [ -f "payload.config.ts" ]; then
        log_success "พบ Payload CMS config"
    else
        log_warning "ไม่พบ payload.config.ts"
    fi
}

#-------------------------------------------------------------------------------
# Check meta tags
#-------------------------------------------------------------------------------

check_meta_tags() {
    echo ""
    echo "=============================================="
    echo "  2. Meta Tags"
    echo "=============================================="

    cd "$PROJECT_PATH"

    local pages_with_title=0
    local pages_with_desc=0
    local pages_with_keywords=0
    local total_pages=0

    for page in src/app/**/page.tsx src/app/**/page.ts src/app/page.tsx src/app/page.ts; do
        if [ -f "$page" ]; then
            total_pages=$((total_pages + 1))

            if grep -q '<title>' "$page" || grep -q '<Title' "$page"; then
                pages_with_title=$((pages_with_title + 1))
            fi

            if grep -q 'description' "$page" || grep -q 'meta.*name="description"' "$page"; then
                pages_with_desc=$((pages_with_desc + 1))
            fi

            if grep -q 'keywords' "$page" || grep -q 'meta.*name="keywords"' "$page"; then
                pages_with_keywords=$((pages_with_keywords + 1))
            fi
        fi
    done

    echo "  Pages ที่มี <title>: $pages_with_title / $total_pages"
    echo "  Pages ที่มี description: $pages_with_desc / $total_pages"
    echo "  Pages ที่มี keywords: $pages_with_keywords / $total_pages"

    if [ $pages_with_title -eq $total_pages ] && [ $total_pages -gt 0 ]; then
        log_success "ทุก page มี title"
    else
        log_warning "บาง page ไม่มี title"
    fi
}

#-------------------------------------------------------------------------------
# Check heading structure
#-------------------------------------------------------------------------------

check_headings() {
    echo ""
    echo "=============================================="
    echo "  3. Heading Structure"
    echo "=============================================="

    cd "$PROJECT_PATH"

    local pages_with_h1=0
    local pages_with_h2=0
    local total_pages=0

    for page in src/app/**/page.tsx src/app/**/page.ts src/app/page.tsx src/app/page.ts; do
        if [ -f "$page" ]; then
            total_pages=$((total_pages + 1))

            if grep -q '<h1' "$page"; then
                pages_with_h1=$((pages_with_h1 + 1))
            fi

            if grep -q '<h2' "$page"; then
                pages_with_h2=$((pages_with_h2 + 1))
            fi
        fi
    done

    echo "  Pages ที่มี <h1>: $pages_with_h1 / $total_pages"
    echo "  Pages ที่มี <h2>: $pages_with_h2 / $total_pages"

    if [ $pages_with_h1 -eq $total_pages ] && [ $total_pages -gt 0 ]; then
        log_success "ทุก page มี h1"
    else
        log_warning "บาง page ไม่มี h1"
    fi
}

#-------------------------------------------------------------------------------
# Check sitemap
#-------------------------------------------------------------------------------

check_sitemap() {
    echo ""
    echo "=============================================="
    echo "  4. Sitemap"
    echo "=============================================="

    cd "$PROJECT_PATH"

    if [ -f "next.config.ts" ] && grep -q 'sitemap' "next.config.ts"; then
        log_success "Sitemap integration ถูกตั้งค่า"
    else
        log_warning "ไม่พบ sitemap integration"
    fi

    if [ -f "public/sitemap.xml" ]; then
        log_success "พบ sitemap.xml"
    else
        log_warning "ไม่พบ sitemap.xml (อาจถูกสร้างตอน build)"
    fi
}

#-------------------------------------------------------------------------------
# Check robots.txt
#-------------------------------------------------------------------------------

check_robots() {
    echo ""
    echo "=============================================="
    echo "  5. Robots.txt"
    echo "=============================================="

    cd "$PROJECT_PATH"

    if [ -f "public/robots.txt" ]; then
        log_success "พบ robots.txt"
        echo "  Content:"
        cat public/robots.txt | sed 's/^/    /'
    else
        log_warning "ไม่พบ robots.txt"
    fi
}

#-------------------------------------------------------------------------------
# Check Open Graph
#-------------------------------------------------------------------------------

check_open_graph() {
    echo ""
    echo "=============================================="
    echo "  6. Open Graph Tags"
    echo "=============================================="

    cd "$PROJECT_PATH"

    local pages_with_og=0
    local total_pages=0

    for page in src/app/**/page.tsx src/app/**/page.ts src/app/page.tsx src/app/page.ts; do
        if [ -f "$page" ]; then
            total_pages=$((total_pages + 1))

            if grep -q 'og:title' "$page" || grep -q 'property="og:' "$page"; then
                pages_with_og=$((pages_with_og + 1))
            fi
        fi
    done

    echo "  Pages ที่มี Open Graph tags: $pages_with_og / $total_pages"

    if [ $pages_with_og -gt 0 ]; then
        log_success "พบ Open Graph tags"
    else
        log_warning "ไม่พบ Open Graph tags"
    fi
}

#-------------------------------------------------------------------------------
# Check Thai language
#-------------------------------------------------------------------------------

check_thai_language() {
    echo ""
    echo "=============================================="
    echo "  7. Thai Language Optimization"
    echo "=============================================="

    cd "$PROJECT_PATH"

    if grep -q 'lang="th"' "src/app"/*.tsx "src/app"/*.ts 2>/dev/null; then
        log_success "พบ lang='th' attribute"
    else
        log_warning "ไม่พบ lang='th' attribute"
    fi

    if grep -q 'Kanit\|Noto Sans Thai' "src/styles/global.css" 2>/dev/null; then
        log_success "พบ Thai font configuration"
    else
        log_warning "ไม่พบ Thai font configuration"
    fi

    if [ -d "src/content" ]; then
        local md_count=$(find src/content -name "*.md" -o -name "*.mdx" | wc -l)
        if [ $md_count -gt 0 ]; then
            log_success "พบ $md_count content files"
        fi
    fi
}

#-------------------------------------------------------------------------------
# Check JSON-LD
#-------------------------------------------------------------------------------

check_json_ld() {
    echo ""
    echo "=============================================="
    echo "  8. JSON-LD Structured Data"
    echo "=============================================="

    cd "$PROJECT_PATH"

    local pages_with_jsonld=0
    local total_pages=0

    for page in src/app/**/page.tsx src/app/**/page.ts src/app/page.tsx src/app/page.ts; do
        if [ -f "$page" ]; then
            total_pages=$((total_pages + 1))

            if grep -q 'application/ld+json' "$page" || grep -q 'JSON-LD\|jsonld' "$page"; then
                pages_with_jsonld=$((pages_with_jsonld + 1))
            fi
        fi
    done

    echo "  Pages ที่มี JSON-LD: $pages_with_jsonld / $total_pages"

    if [ $pages_with_jsonld -gt 0 ]; then
        log_success "พบ JSON-LD structured data"
    else
        log_warning "ไม่พบ JSON-LD structured data"
    fi
}

#-------------------------------------------------------------------------------
# Check image optimization
#-------------------------------------------------------------------------------

check_images() {
    echo ""
    echo "=============================================="
    echo "  9. Image Optimization"
    echo "=============================================="

    cd "$PROJECT_PATH"

    local images_without_alt=0
    local total_images=0

    if [ -d "src/assets" ] || [ -d "public/images" ]; then
        local search_dir="src/assets"
        [ ! -d "$search_dir" ] && search_dir="public/images"

        for img in $(find "$search_dir" -type f \( -name "*.jpg" -o -name "*.jpeg" -o -name "*.png" -o -name "*.webp" \) 2>/dev/null | head -20); do
            total_images=$((total_images + 1))
        done

        echo "  พบ $total_images images"
        log_success "Images ถูกจัดเก็บอย่างถูกต้อง"
    else
        log_warning "ไม่พบ images directory"
    fi
}

#-------------------------------------------------------------------------------
# Summary
#-------------------------------------------------------------------------------

show_summary() {
    echo ""
    echo "=============================================="
    echo "  SEO Audit Summary"
    echo "=============================================="
    echo ""
    echo "  Project: $PROJECT_PATH"
    echo "  หากต้องการรายงาน GEO เพิ่มเติม ใช้คำสั่ง:"
    echo ""
    echo "    /skill seo-geo"
    echo ""
    echo "  หากต้องการวิเคราะห์ SEO แบบละเอียด ใช้คำสั่ง:"
    echo ""
    echo "    /skill seo-analyzers"
    echo ""
}

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

main() {
    echo "=============================================="
    echo "  SEO Audit Tool"
    echo "  Next.js + Payload CMS"
    echo "=============================================="
    echo ""

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

    check_requirements
    check_project_structure
    check_meta_tags
    check_headings
    check_sitemap
    check_robots
    check_open_graph
    check_thai_language
    check_json_ld
    check_images
    show_summary

    echo ""
    echo "=============================================="
    log_success "SEO Audit เสร็จสมบูรณ์!"
    echo "=============================================="
}

main "$@"
