"""VPS Agent 主入口：采集本机信息并上报到中心服务器

环境变量（建议写入 /etc/vps-agent.env）：
  VPS_MANAGER_URL  中心地址，如 http://100.89.0.11:8000
  VPS_ASSET_ID     本机对应的资产 ID
  VPS_AGENT_KEY    Agent Key（中心配置了 AGENT_KEY 时必填）
  VPS_AGENT_RETRY  上报失败重试次数（默认 2，指数退避）
"""

import os
import sys
import time

import httpx

from collector import collect_metrics, collect_security, collect_server_info


def main() -> int:
    url = os.environ.get("VPS_MANAGER_URL", "").rstrip("/")
    asset_id = os.environ.get("VPS_ASSET_ID", "")
    key = os.environ.get("VPS_AGENT_KEY", "")
    max_retry = int(os.environ.get("VPS_AGENT_RETRY", "2"))

    if not url or not asset_id:
        print("错误：需设置 VPS_MANAGER_URL 和 VPS_ASSET_ID")
        return 1

    payload = {
        "asset_id": int(asset_id),
        "metrics": collect_metrics(),
        "server_info": collect_server_info(),
        "security": collect_security(),
    }
    headers = {"X-Agent-Key": key} if key else {}

    for attempt in range(max_retry + 1):
        try:
            resp = httpx.post(
                f"{url}/api/agent/report", json=payload, headers=headers, timeout=30
            )
            print(f"上报完成 HTTP {resp.status_code}: {resp.text}")
            resp.raise_for_status()
            return 0
        except Exception as e:  # noqa: BLE001
            if attempt < max_retry:
                wait = 2 ** attempt
                print(f"上报失败（{attempt + 1}/{max_retry + 1}），{wait}s 后重试: {e}")
                time.sleep(wait)
            else:
                print(f"上报失败（已重试 {max_retry} 次）: {e}")
                return 1
    return 1


if __name__ == "__main__":
    sys.exit(main())
