#!/bin/bash

# Upload 12 articles to 4 WordPress sites
# Usage: ./upload_articles.sh

cd /home/mantapman/.hermes/profiles/atun/workspace/artikel_seo

upload_post() {
    local domain="$1"
    local app_pw="$2"
    local file="$3"
    
    # Parse header
    local title=$(head -1 "$file" | sed 's/^# //')
    local meta=$(head -2 "$file" | tail -1 | sed 's/^# //')
    local keyphrase=$(grep "^# Keyphrase:" "$file" | sed 's/^# Keyphrase: //')
    local slug=$(grep "^# Slug:" "$file" | sed 's/^# Slug: //')
    
    # Parse body: remove header lines, [WA Button], ## Tags
    local body=$(sed '1,/^\[H1\]/d' "$file" | sed '/^\[WA Button\]/,$d' | sed '/^## Tags/,$d')
    
    # Convert markdown headings to HTML
    body=$(echo "$body" | sed 's/^\[H1\] \(.*\)$/<h1>\1<\/h1>/')
    body=$(echo "$body" | sed 's/^## \(.*\)$/<h2>\1<\/h2>/')
    body=$(echo "$body" | sed 's/^### \(.*\)$/<h3>\1<\/h3>/')
    
    # Wrap in Gutenberg blocks
    local html=""
    local IFS=$'\n'
    local in_heading=false
    for line in $body; do
        line=$(echo "$line" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        if [[ -z "$line" ]]; then
            continue
        elif [[ "$line" == \<h* ]]; then
            if $in_heading; then
                html+="</p>"
                in_heading=false
            fi
            html+="<!-- wp:heading -->$line<!-- /wp:heading -->"
        else
            if ! $in_heading; then
                html+="<!-- wp:paragraph --><p>"
                in_heading=true
            else
                html+=" "
            fi
            html+="$line"
        fi
    done
    if $in_heading; then
        html+="</p><!-- /wp:paragraph -->"
    fi
    
    # Add WA button
    local wa_url=$(grep "^# WA Button:" "$file" | sed 's/^# WA Button: //')
    if [[ ! -z "$wa_url" && "$wa_url" != \(* ]]; then
        html+='<!-- wp:buttons --><div class="wp-block-buttons"><!-- wp:button --><div class="wp-block-button"><a class="wp-block-button__link" href="'$wa_url'">Konsultasi Gratis via WhatsApp</a></div><!-- /wp:button --></div><!-- /wp:buttons -->'
    fi
    
    # Count words
    local wc=$(echo "$body" | wc -w)
    
    # Create JSON
    local json=$(cat << EOF
{
  "title": "$title",
  "content": $(echo "$html" | python3 -c "import sys,json; print(json.dumps(sys.stdin.read()))"),
  "slug": "$slug",
  "status": "publish",
  "meta": {
    "_yoast_wpseo_title": "$title",
    "_yoast_wpseo_metadesc": "$meta",
    "_yoast_wpseo_focuskw": "$keyphrase"
  }
}
EOF
)
    
    echo "📤 $domain / $slug (${wc} kata)"
    
    # Upload
    local resp=$(curl -s -w "\n%{http_code}" -X POST "https://$domain/wp-json/wp/v2/posts" \
        -u "bambangbot:$app_pw" \
        -H "Content-Type: application/json" \
        -d "$json" 2>&1)
    
    local http_code=$(echo "$resp" | tail -1)
    local body=$(echo "$resp" | head -n -1)
    
    if [[ "$http_code" == "201" || "$http_code" == "200" ]]; then
        local post_id=$(echo "$body" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])" 2>/dev/null)
        local post_url=$(echo "$body" | python3 -c "import sys,json; print(json.load(sys.stdin)['link'])" 2>/dev/null)
        echo "   ✅ Post $post_id → $post_url"
    else
        echo "   ❌ HTTP $http_code: $(echo "$body" | head -c 200)"
    fi
}

# STUDIOSOFT
echo ""
echo "═══════════════════════════════════════════════"
echo "📍 STUDIOSOFT (studiosoft.id)"
echo "═══════════════════════════════════════════════"
upload_post "studiosoft.id" "q26r RePo BVy6 pwU2 F3z7 ouyl" "studiosoft_seo-untuk-umkm.txt"
upload_post "studiosoft.id" "q26r RePo BVy6 pwU2 F3z7 ouyl" "studiosoft_pentingnya-website-untuk-bisnis.txt"
upload_post "studiosoft.id" "q26r RePo BVy6 pwU2 F3z7 ouyl" "studiosoft_ai-untuk-marketing.txt"

# APOTEK
echo ""
echo "═══════════════════════════════════════════════"
echo "📍 APOTEK (www.apotekpamekasan.com)"
echo "═══════════════════════════════════════════════"
upload_post "www.apotekpamekasan.com" "Rab8 qmxV gJ1k yDY3 9ske utCz" "apotek_cara-mengatasi-demam-anak.txt"
upload_post "www.apotekpamekasan.com" "Rab8 qmxV gJ1k yDY3 9ske utCz" "apotek_vitamin-untuk-daya-tahan-tubuh.txt"
upload_post "www.apotekpamekasan.com" "Rab8 qmxV gJ1k yDY3 9ske utCz" "apotek_bahaya-antibiotik-tanpa-resep-dokter.txt"

# TTA LAW
echo ""
echo "═══════════════════════════════════════════════"
echo "📍 TSLaw (ttalawfirm.id)"
echo "═══════════════════════════════════════════════"
upload_post "ttalawfirm.id" "EFKm EYGx VQCP Y9go ncPr uM2Y" "ttalaw_panduan-mendirikan-pt-untuk-umkm.txt"
upload_post "ttalawfirm.id" "EFKm EYGx VQCP Y9go ncPr uM2Y" "ttalaw_kontrak-bisnis-yang-aman.txt"
upload_post "ttalawfirm.id" "EFKm EYGx VQCP Y9go ncPr uM2Y" "ttalaw_cara-daftar-merek-dagang.txt"

# DAS
echo ""
echo "═══════════════════════════════════════════════"
echo "📍 DAS (dasindonesia.com)"
echo "═══════════════════════════════════════════════"
upload_post "dasindonesia.com" "u3a1 G2pQ 3SWY f0zI OlGP YAjU" "das_kapan-mobil-perlu-engine-overhaul.txt"
upload_post "dasindonesia.com" "u3a1 G2pQ 3SWY f0zI OlGP YAjU" "das_penyebab-mesin-mobil-overheat.txt"
upload_post "dasindonesia.com" "u3a1 G2pQ 3SWY f0zI OlGP YAjU" "das_cara-merawat-mesin-mobil-agar-awet.txt"

echo ""
echo "✅ SELESAI! Semua artikel telah diupload."
