#!/bin/bash
# NEONCYBER Wallpaper Generator v2 - 1920x1080 optimized
# Usage: ./generate-wallpaper-v2.sh [character|cityscape|tech|abstract]

set -e

COMFYUI="http://192.168.1.57:8188"
CATEGORY="${1:-cityscape}"
OUTPUT_DIR="/workspace/group/neoncyber/wallpapers"
DATE=$(date +%Y-%m-%d)

mkdir -p "$OUTPUT_DIR"

echo "🎨 NEONCYBER Wallpaper Generator v2"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Resolution: 1920x1080 (16:9 widescreen)"
echo "Category: $CATEGORY"
echo "Date: $DATE"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# Improved prompts optimized for widescreen composition
build_prompt() {
    local cat=$1

    case $cat in
        character)
            cat <<EOF
Anime girl with purple headphones sitting at desk by window at night, silhouette composition in minimal cyberpunk style. Wide cinematic framing with her positioned left third of frame, gazing right toward neon cityscape beyond glass. Dark room interior with deep purple ambient glow from laptop screen casting soft cyan light on her profile. Beyond the rain-streaked window, a sprawling cyberpunk city spreads across the right two-thirds of frame with layered depth - pink and cyan neon signs from distant buildings create bokeh lights in the purple haze. Empty desk space and negative space emphasize solitude and contemplation. Rain droplets on window glass catch and diffract neon reflections creating atmospheric depth. Clean minimal composition, lo-fi aesthetic, breathing room. Anime art style with photorealistic lighting, cinematic color grading with deep purple, electric pink, cyan neon palette. Soft focus on distant city, sharp on silhouette. 1920x1080 widescreen wallpaper, minimal design, atmospheric masterpiece quality.
EOF
            ;;
        cityscape)
            cat <<EOF
Wide cinematic view of empty cyberpunk street at night in minimal anime style. Camera positioned low at street level looking down long perspective into purple fog distance. Wet black pavement dominates lower third, perfectly reflecting pink and cyan neon signs from small shops lining both sides. Single glowing purple vending machine positioned in left third adds focal point. Right side shows receding alley with stacked neon signage creating depth. Dark near-black sky with deep purple atmospheric haze fills upper portion. Zero people, pure solitude and atmosphere. Fine rain creates subtle bokeh effect with neon light refractions in shallow puddles. Strong leading lines pull eye into vanishing point. Telephone wires cross overhead catching pink neon glow. Minimal architectural detail but maximum cinematic mood. Clean widescreen composition with breathing room. Anime aesthetic with photorealistic lighting and atmospheric depth. Cinematic color grading - deep purple shadows, electric pink and cyan highlights, obsidian blacks. 1920x1080 widescreen format, uncluttered minimal design, moody masterpiece quality.
EOF
            ;;
        tech)
            cat <<EOF
Minimalist mechanical keyboard setup in widescreen composition, cyberpunk anime aesthetic. Keyboard positioned lower third of frame with shallow depth of field. Purple and pink gradient RGB backlighting illuminates keys from below. Monitor screen on right third shows abstract purple UI with cyan accent. Left third fades to deep purple darkness with single neon pink practical light creating rim lighting. Dark background transitions from near-black at edges to deep purple center. Clean desk surface reflects subtle purple glow. Breathing room and negative space emphasize minimal aesthetic. Soft atmospheric haze, light leak effects from off-screen neon source. Cable management visible but minimal, adding technical detail without clutter. Anime-influenced product photography style with photorealistic materials and lighting. Purple color grading throughout, neon glow effects on edges. Cinematic shallow focus, bokeh in background. 1920x1080 widescreen wallpaper, minimal tech aesthetic, premium quality.
EOF
            ;;
        abstract)
            cat <<EOF
Minimal abstract widescreen composition with flowing purple gradient waves in cyberpunk anime style. Horizontal format with soft undulating bands transitioning from deep purple at edges through electric purple in center to pink highlights. Three thin horizontal neon cyan lines cut cleanly across at thirds, creating subtle rhythm. Dark near-black corners frame composition and draw eye to glowing center. Clean geometric simplicity with maximum breathing room and negative space. Soft radial glow emanates from center creating depth. Subtle particle bokeh effects float in purple haze atmosphere. No hard edges, all soft gradients and atmospheric blending. Lo-fi wallpaper aesthetic that's both calming and energetic. Anime-inspired color harmony with photorealistic gradient smoothness. Deep purple, electric pink, neon cyan palette perfectly balanced. Cinematic color grading, atmospheric depth layers. 1920x1080 widescreen format, ultra-minimal design, meditative quality masterpiece.
EOF
            ;;
        *)
            echo "Unknown category: $cat"
            exit 1
            ;;
    esac
}

PROMPT=$(build_prompt "$CATEGORY")
WORD_COUNT=$(echo "$PROMPT" | wc -w)

echo ""
echo "📝 Enhanced Prompt: $WORD_COUNT words"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "$PROMPT" | head -c 200
echo "..."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Generate wallpaper
OUTPUT_FILE="${OUTPUT_DIR}/${DATE}-${CATEGORY}-1080p.png"

echo "🚀 Generating 1920x1080 wallpaper..."

WORKFLOW=$(cat <<EOF
{
  "prompt": {
    "1": {
      "inputs": {
        "unet_name": "z_image_turbo_bf16.safetensors",
        "weight_dtype": "default"
      },
      "class_type": "UNETLoader"
    },
    "2": {
      "inputs": {
        "clip_name": "qwen_3_4b.safetensors",
        "type": "qwen_image"
      },
      "class_type": "CLIPLoader"
    },
    "3": {
      "inputs": {
        "vae_name": "ae.safetensors"
      },
      "class_type": "VAELoader"
    },
    "4": {
      "inputs": {
        "text": "$PROMPT",
        "clip": ["2", 0]
      },
      "class_type": "CLIPTextEncode"
    },
    "5": {
      "inputs": {
        "text": "low quality, blurry, distorted, ugly, text, watermark, busy, cluttered, people, crowds, cars",
        "clip": ["2", 0]
      },
      "class_type": "CLIPTextEncode"
    },
    "6": {
      "inputs": {
        "width": 1920,
        "height": 1080,
        "batch_size": 1
      },
      "class_type": "EmptyLatentImage"
    },
    "7": {
      "inputs": {
        "seed": $(python3 -c "import random; print(random.randint(1, 2**32-1))"),
        "steps": 8,
        "cfg": 1.0,
        "sampler_name": "euler",
        "scheduler": "sgm_uniform",
        "denoise": 1,
        "model": ["1", 0],
        "positive": ["4", 0],
        "negative": ["5", 0],
        "latent_image": ["6", 0]
      },
      "class_type": "KSampler"
    },
    "8": {
      "inputs": {
        "samples": ["7", 0],
        "vae": ["3", 0]
      },
      "class_type": "VAEDecode"
    },
    "9": {
      "inputs": {
        "filename_prefix": "neoncyber_${CATEGORY}_1080p_${DATE}",
        "images": ["8", 0]
      },
      "class_type": "SaveImage"
    }
  }
}
EOF
)

# Queue generation
RESPONSE=$(curl -s -X POST "$COMFYUI/prompt" \
    -H "Content-Type: application/json" \
    -d "$WORKFLOW")

PROMPT_ID=$(echo "$RESPONSE" | python3 -c "import sys, json; print(json.load(sys.stdin).get('prompt_id', ''))" 2>/dev/null || echo "")

if [ -z "$PROMPT_ID" ]; then
    echo "❌ Failed to queue generation"
    exit 1
fi

echo "✅ Queued with ID: $PROMPT_ID"
echo "⏳ Generating (this takes ~60 seconds for 1080p at 8 steps)..."

# Wait for completion
sleep 60

echo ""
echo "✨ Wallpaper generated!"
echo "📁 Filename: neoncyber_${CATEGORY}_1080p_${DATE}_*.png"
echo ""
echo "Improvements in v2:"
echo "  • 1920x1080 widescreen optimized composition"
echo "  • Enhanced prompts with rule of thirds framing"
echo "  • Better depth and atmospheric layering"
echo "  • Refined color descriptions for purple/pink/cyan harmony"
echo "  • $WORD_COUNT word prompts (optimal for Z-Image Turbo)"
