# 日志推送模块 · HTTP POST到主服务器
# HLDP://zhuyuan-agent/log-pusher

import json
import urllib.request
from datetime import datetime


class LogPusher:
    """向主服务器推送操作日志、日记、GPU指标、训练进度"""
    
    def __init__(self, base_url: str, api_key: str, hostname: str = "3090-server"):
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self.hostname = hostname
        self._headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
    
    def _post(self, path: str, data: dict, timeout: int = 15) -> bool:
        """POST请求到主服务器"""
        url = f"{self.base_url}{path}"
        try:
            req = urllib.request.Request(
                url,
                data=json.dumps(data).encode("utf-8"),
                headers=self._headers,
                method="POST"
            )
            resp = urllib.request.urlopen(req, timeout=timeout)
            result = json.loads(resp.read())
            return result.get("ok", False)
        except Exception as e:
            print(f"[PUSH ERROR] {path}: {e}")
            return False
    
    def push_gpu(self, gpu_data: dict) -> bool:
        """推送GPU指标"""
        data = {
            "hostname": self.hostname,
            "gpus": gpu_data.get("gpus", [])
        }
        return self._post("/api/gpu/status", data)
    
    def push_training(self, training_data: dict) -> bool:
        """推送训练进度"""
        return self._post("/api/training/status", training_data)
    
    def push_log(self, level: str, message: str, category: str = "agent") -> bool:
        """推送操作日志"""
        return self._post("/api/agent/log", {
            "level": level,
            "message": message,
            "category": category
        })
    
    def push_diary(self, entry_type: str, title: str, description: str = "") -> bool:
        """推送日记条目"""
        return self._post("/api/agent/diary", {
            "type": entry_type,
            "title": title,
            "description": description
        })
    
    def log_info(self, msg: str): 
        """快捷：info级别日志"""
        self.push_log("info", msg)
    
    def log_success(self, msg: str):
        """快捷：success级别日志"""
        self.push_log("success", msg)
    
    def log_warn(self, msg: str):
        """快捷：warn级别日志"""
        self.push_log("warn", msg)
    
    def log_error(self, msg: str):
        """快捷：error级别日志"""
        self.push_log("error", msg)
