#!/bin/bash
# UE5 项目设置脚本
# 此脚本用于初始化 UE5 项目的 Cesium 配置

set -e

echo "=========================================="
echo "智能星球计划 - UE5 项目初始化"
echo "=========================================="
echo ""

# 检查是否安装了 UE5
if ! command -v ue5 &> /dev/null && ! command -v UnrealEditor &> /dev/null; then
    echo "⚠️  未检测到 UE5 安装"
    echo "请从 Epic Games Launcher 安装 Unreal Engine 5.3+"
    echo ""
fi

# 创建配置文件
CONFIG_FILE="Config/PlanetConfig.ini"
if [ ! -f "$CONFIG_FILE" ]; then
    echo "📝 创建配置文件..."
    cat > "$CONFIG_FILE" << 'EOF'
# UE5 项目配置文件
# Cesium ion 访问令牌

# Cesium ion Token
# 请从 https://cesium.com/ion/ 获取你的 token
CESIUM_ION_TOKEN=YOUR_TOKEN_HERE

# Cesium ion 默认服务器
CESIUM_ION_DEFAULT_SERVER=https://ion.cesium.com

# 后端 API 地址
BACKEND_API_URL=http://localhost:8000
BACKEND_WS_URL=ws://localhost:8000
EOF
    echo "✅ 已创建 $CONFIG_FILE"
    echo ""
else
    echo "✅ 配置文件已存在"
fi

# 创建蓝图占位符
echo ""
echo "📦 创建蓝图脚本..."

# BP_GlobeController.py (占位符)
cat > "Source/PlanetAPI/Private/PlanetAPIClient.cpp" << 'CPP'
// Planet API Client
// 用于连接后端 WebSocket 服务

#include "PlanetAPIClient.h"
#include "IWebSocket.h"
#include "WebSocketsModule.h"

void UPlanetAPIClient::Connect(FString URL)
{
    if (!FModuleManager::Get().IsModuleLoaded("WebSockets"))
    {
        FModuleManager::Get().LoadModule("WebSockets");
    }
    
    Socket = FWebSocketsModule::Get().CreateWebSocket(URL);
    
    Socket->OnConnected().AddLambda([](){
        UE_LOG(LogTemp, Log, TEXT("WebSocket Connected!"));
    });
    
    Socket->OnMessage().AddLambda([this](FString Message){
        HandleMessage(Message);
    });
    
    Socket->OnClosed().AddLambda([](int32 StatusCode, const FString& Reason, bool bWasClean){
        UE_LOG(LogTemp, Warning, TEXT("WebSocket Closed: %d - %s"), StatusCode, *Reason);
    });
    
    Socket->Connect();
}

void UPlanetAPIClient::Disconnect()
{
    if (Socket.IsValid())
    {
        Socket->Close();
    }
}

void UPlanetAPIClient::HandleMessage(FString Message)
{
    // 解析 JSON 消息
    TSharedPtr<FJsonObject> JsonParsed;
    TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Message);
    
    if (FJsonSerializer::Deserialize(Reader, JsonParsed) && JsonParsed.IsValid())
    {
        FString Type = JsonParsed->GetStringField("type");
        
        if (Type == "update")
        {
            OnDataReceived.Broadcast(JsonParsed);
        }
        else if (Type == "alarm")
        {
            OnAlarmReceived.Broadcast(JsonParsed);
        }
    }
}
CPP

echo "✅ 已创建 PlanetAPIClient.cpp"

echo ""
echo "=========================================="
echo "✅ UE5 项目初始化完成！"
echo "=========================================="
echo ""
echo "📋 下一步操作："
echo "1. 打开 Unreal Engine 5"
echo "2. 打开项目目录中的 Planet.uproject"
echo "3. 从 Marketplace 安装 Cesium for Unreal 插件"
echo "4. 在项目设置中配置 Cesium ion Token"
echo "5. 开始开发蓝图和可视化组件"
echo ""
echo "📖 详细文档请查看：docs/ue5_development_plan.md"
echo ""
