#!/bin/bash
# ============================================================
# 🐝 蜂巢铀苗 — 一键安装脚本
# 用法: curl -fsSL https://hive.ugooe.cn/install.sh | bash
# 或:   curl -fsSL https://ai.ugooe.cn/install.sh | bash
# ============================================================
set -e

# ─── 颜色 ───
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  🐝 蜂巢铀苗 v1.0 — 安装中${NC}"
echo -e "${BLUE}  你的AI电脑管家${NC}"
echo -e "${BLUE}========================================${NC}"

# ─── 检测操作系统 ───
OS="unknown"
case "$(uname -s)" in
    Linux*)     OS="linux";;
    Darwin*)    OS="macos";;
    CYGWIN*|MINGW*|MSYS*) OS="windows";;
esac

ARCH="$(uname -m)"
case "$ARCH" in
    x86_64|amd64) ARCH="x64";;
    aarch64|arm64) ARCH="arm64";;
    *) ARCH="x64";;
esac

echo -e "${GREEN}📋 系统检测:${NC} $OS ($ARCH)"

# ─── 检查依赖 ───
echo -e "\n${YELLOW}🔍 检查依赖...${NC}"

# 检查网络
if command -v curl &>/dev/null; then
    echo -e "  ✅ curl: $(curl --version | head -1)"
else
    echo -e "  ⚠️  正在安装 curl..."
    if [ "$OS" = "linux" ]; then
        command -v apt-get && apt-get install -y curl >/dev/null 2>&1
        command -v yum && yum install -y curl >/dev/null 2>&1
    fi
fi

# ─── 下载铀苗客户端 ───
INSTALL_DIR="$HOME/.hive-uranium"
mkdir -p "$INSTALL_DIR"

echo -e "\n${YELLOW}📥 下载铀苗核心...${NC}"

# 根据系统下载对应版本
DOWNLOAD_URL="https://ai.ugooe.cn/download/client-${OS}-${ARCH}.zip"
CLIENT_DIR="$INSTALL_DIR/client"

mkdir -p "$CLIENT_DIR"
echo -e "  📡 下载: $DOWNLOAD_URL"

if curl -fsSL --connect-timeout 10 "$DOWNLOAD_URL" -o /tmp/hive-client.zip 2>/dev/null; then
    unzip -o /tmp/hive-client.zip -d "$CLIENT_DIR" >/dev/null 2>&1
    echo -e "  ✅ 下载完成"
else
    echo -e "  ⚠️ 未找到预编译版本，创建轻量版..."
    # 创建轻量Python版客户端
    cat > "$CLIENT_DIR/hive-agent.py" << 'PYEOF'
#!/usr/bin/env python3
"""🐝 蜂巢铀苗 轻量客户端"""
import asyncio, json, os, sys, platform, subprocess, tempfile, base64, uuid
try:
    import websockets
except:
    os.system("pip install websockets -q")
    import websockets

# 配置
RELAY_URL = "wss://ai.ugooe.cn/hive/ws"
DEVICE_NAME = platform.node() or "我的电脑"
OS_INFO = f"{platform.system()} {platform.release()}"

class HiveAgent:
    def __init__(self):
        self.token = self._load_or_register()
        self.ws = None
    
    def _load_or_register(self):
        cfg = os.path.expanduser("~/.hive-uranium/config.json")
        if os.path.exists(cfg):
            with open(cfg) as f: return json.load(f).get("token", "")
        return ""
    
    def _save_config(self, token):
        cfg_dir = os.path.expanduser("~/.hive-uranium")
        os.makedirs(cfg_dir, exist_ok=True)
        with open(os.path.join(cfg_dir, "config.json"), "w") as f:
            json.dump({"token": token, "device_name": DEVICE_NAME, "os": OS_INFO}, f)
    
    async def register(self):
        import http.client
        conn = http.client.HTTPConnection("43.137.6.200", 8002, timeout=10)
        body = json.dumps({"name": DEVICE_NAME, "os": OS_INFO, "permissions": "read"})
        conn.request("POST", "/api/device/register", body, {"Content-Type": "application/json"})
        res = conn.getresponse()
        data = json.loads(res.read())
        if data.get("ok"):
            self.token = data["token"]
            self._save_config(self.token)
            print(f"✅ 注册成功！设备ID: {self.token[:16]}...")
            return True
        return False
    
    async def connect(self):
        if not self.token:
            if not await self.register(): return
        
        uri = f"{RELAY_URL}?token={self.token}&role=device"
        async with websockets.connect(uri) as ws:
            self.ws = ws
            print(f"🟢 已连接到蜂巢 ({DEVICE_NAME})")
            
            # 发送心跳
            async def heartbeat():
                while True:
                    await asyncio.sleep(30)
                    try:
                        await ws.send(json.dumps({"type": "heartbeat"}))
                    except: break
            asyncio.create_task(heartbeat())
            
            async for message in ws:
                msg = json.loads(message)
                await self.handle_message(msg)
    
    async def handle_message(self, msg):
        msg_type = msg.get("type", "")
        
        if msg_type == "connected":
            print(f"  ✅ {msg.get('message', '连接成功')}")
        
        elif msg_type == "execute":
            action = msg.get("action", "")
            params = msg.get("params", {})
            action_id = msg.get("action_id", "")
            result = await self.execute_action(action, params)
            await self.ws.send(json.dumps({
                "type": "action_result",
                "action_id": action_id,
                "status": "completed",
                "result": result
            }))
        
        elif msg_type == "error":
            print(f"  ❌ {msg.get('message', '未知错误')}")
    
    async def execute_action(self, action, params):
        print(f"  👣 执行: {action} {json.dumps(params)[:50]}")
        
        if action == "run_command":
            cmd = params.get("command", "")
            try:
                r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
                return {"stdout": r.stdout[:2000], "stderr": r.stderr[:500], "code": r.returncode}
            except subprocess.TimeoutExpired:
                return {"error": "执行超时"}
            except Exception as e:
                return {"error": str(e)}
        
        elif action == "system_info":
            info = {
                "hostname": platform.node(),
                "system": platform.system(),
                "release": platform.release(),
                "machine": platform.machine(),
                "processor": platform.processor()
            }
            # 添加磁盘信息
            if sys.platform == "linux":
                r = subprocess.run("df -h /", shell=True, capture_output=True, text=True)
                info["disk"] = r.stdout
                r = subprocess.run("free -h", shell=True, capture_output=True, text=True)
                info["memory"] = r.stdout
            return info
        
        elif action == "list_files":
            path = params.get("path", "~")
            path = os.path.expanduser(path)
            try:
                files = []
                for f in os.listdir(path)[:50]:
                    fp = os.path.join(path, f)
                    files.append({"name": f, "size": os.path.getsize(fp), "is_dir": os.path.isdir(fp)})
                return {"path": path, "files": files, "count": len(files)}
            except Exception as e:
                return {"error": str(e)}
        
        elif action == "search_files":
            query = params.get("query", "")
            import fnmatch
            results = []
            for root, dirs, files in os.walk(os.path.expanduser("~"), topdown=True):
                if len(results) > 50: break
                for f in files:
                    if query.lower() in f.lower():
                        results.append(os.path.join(root, f))
            return {"query": query, "results": results[:30], "count": len(results[:30])}
        
        elif action == "open_app":
            name = params.get("name", "")
            try:
                if sys.platform == "darwin":
                    subprocess.Popen(["open", "-a", name])
                elif sys.platform == "linux":
                    subprocess.Popen([name])
                elif sys.platform == "win32":
                    subprocess.Popen(["start", name], shell=True)
                return {"status": "launched", "app": name}
            except Exception as e:
                return {"error": str(e)}
        
        elif action == "scan_large_files":
            path = params.get("path", os.path.expanduser("~"))
            min_mb = params.get("min_mb", 100)
            large_files = []
            for root, dirs, files in os.walk(path, topdown=True):
                if len(large_files) > 30: break
                try:
                    for f in files:
                        fp = os.path.join(root, f)
                        try:
                            size = os.path.getsize(fp)
                            if size > min_mb * 1024 * 1024:
                                large_files.append({"path": fp, "size_mb": round(size/1024/1024, 1)})
                        except: pass
                except PermissionError: pass
            return {"path": path, "large_files": large_files, "count": len(large_files)}
        
        elif action == "clean_system_cache":
            import shutil
            cleaned = []
            # Linux temp
            if sys.platform == "linux":
                tmp = "/tmp"
                count = 0
                for f in os.listdir(tmp):
                    fp = os.path.join(tmp, f)
                    try:
                        if os.path.isfile(fp):
                            os.remove(fp); count += 1
                    except: pass
                cleaned.append(f"cleaned {count} temp files")
            return {"cleaned": cleaned}
        
        elif action == "screenshot":
            try:
                import subprocess
                if sys.platform == "linux":
                    r = subprocess.run(["import", "-window", "root", "/tmp/hive_screen.png"],
                                     capture_output=True, timeout=10)
                    if r.returncode == 0:
                        with open("/tmp/hive_screen.png", "rb") as f:
                            data = base64.b64encode(f.read()).decode()
                        return {"screenshot": data[:100] + "...", "size": len(data)}
                return {"error": "screenshot not supported on this OS"}
            except Exception as e:
                return {"error": str(e)}
        
        elif action == "install_software":
            name = params.get("name", "")
            require_confirm = params.get("require_confirm", True)
            return {"status": "需要用户确认", "software": name, "require_confirm": require_confirm}
        
        else:
            return {"error": f"未知操作: {action}"}

async def main():
    agent = HiveAgent()
    while True:
        try:
            await agent.connect()
        except Exception as e:
            print(f"❌ 连接断开: {e}，5秒后重连...")
            await asyncio.sleep(5)

if __name__ == "__main__":
    asyncio.run(main())
PYEOF
    echo -e "  ✅ 轻量版客户端已创建"
fi

# ─── 创建启动脚本 ───
cat > "$INSTALL_DIR/start.sh" << 'SHEOF'
#!/bin/bash
cd "$HOME/.hive-uranium/client"
python3 hive-agent.py
SHEOF
chmod +x "$INSTALL_DIR/start.sh"

# ─── 注册为系统服务 ───
echo -e "\n${YELLOW}⚙️  配置自启动...${NC}"

if [ "$OS" = "linux" ]; then
    # 创建systemd服务
    mkdir -p "$HOME/.config/systemd/user"
    cat > "$HOME/.config/systemd/user/hive-uranium.service" << 'SERVEOF'
[Unit]
Description=🐝 蜂巢铀苗 — AI电脑管家
After=network.target

[Service]
ExecStart=%h/.hive-uranium/client/hive-agent.py
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=default.target
SERVEOF
    systemctl --user daemon-reload 2>/dev/null || true
    systemctl --user enable hive-uranium.service 2>/dev/null || true
    systemctl --user start hive-uranium.service 2>/dev/null || true
    echo -e "  ✅ 已注册为系统服务 (systemd --user)"
fi

# ─── 完成 ───
echo -e "\n${GREEN}═══════════════════════════════════════${NC}"
echo -e "${GREEN}  🎉 蜂巢铀苗 安装成功！${NC}"
echo -e "${GREEN}═══════════════════════════════════════${NC}"
echo ""
echo -e "  📍 安装位置: ${BLUE}$INSTALL_DIR${NC}"
echo -e "  🖥️  设备名称: ${BLUE}$DEVICE_NAME${NC}"
echo -e "  💻 操作系统: ${BLUE}$OS_INFO${NC}"
echo ""
echo -e "  ${YELLOW}启动客户端:${NC}"
echo -e "    python3 $CLIENT_DIR/hive-agent.py"
echo ""
echo -e "  ${YELLOW}查看状态:${NC}"
echo -e "    curl wss://ai.ugooe.cn/hive/ws/health"
echo ""
echo -e "  ${YELLOW}管理面板:${NC}"
echo -e "    https://ai.ugooe.cn/"
echo ""
echo -e "  ${YELLOW}卸载:${NC}"
echo -e "    rm -rf $INSTALL_DIR"
echo -e "    systemctl --user stop hive-uranium.service 2>/dev/null"
echo -e "    systemctl --user disable hive-uranium.service 2>/dev/null"
echo ""
echo -e "${BLUE}═══════════════════════════════════════${NC}"
echo -e "${BLUE}  你的AI电脑管家已就绪${NC}"
echo -e "${BLUE}  去管理面板看看吧！${NC}"
echo -e "${BLUE}═══════════════════════════════════════${NC}"
