import { fail, guard, ok } from "@/lib/api";
import { exec } from "@/lib/ssh";

// Endpoint trả metrics realtime từ host: CPU, RAM, Disk, load avg, uptime.
// Không lưu vào DB — fetch on-demand mỗi lần UI mở.

const SCRIPT = `python3 - <<'PY'
import os, json, re

def read(path):
    try:
        with open(path) as f: return f.read()
    except Exception: return ""

# CPU: tính % busy qua /proc/stat snapshot
def cpu_percent():
    def snap():
        line = read("/proc/stat").splitlines()[0]
        nums = [int(x) for x in line.split()[1:]]
        idle = nums[3] + nums[4]
        total = sum(nums)
        return idle, total
    a = snap()
    import time; time.sleep(0.25)
    b = snap()
    didle = b[0] - a[0]; dtotal = b[1] - a[1]
    return round(100.0 * (1 - didle / dtotal), 1) if dtotal else 0.0

def mem():
    info = {}
    for line in read("/proc/meminfo").splitlines():
        m = re.match(r"^(\\S+):\\s+(\\d+)\\s+kB", line)
        if m: info[m.group(1)] = int(m.group(2)) * 1024
    total = info.get("MemTotal", 0)
    avail = info.get("MemAvailable", 0)
    used = total - avail
    return {"total": total, "used": used, "free": avail, "percent": round(100.0 * used / total, 1) if total else 0}

def disk():
    out = []
    try:
        with os.popen("df -B1 -P -x tmpfs -x devtmpfs -x squashfs -x overlay 2>/dev/null") as f:
            lines = f.read().strip().splitlines()[1:]
        for ln in lines:
            parts = ln.split()
            if len(parts) >= 6 and parts[5] in ("/", "/data", "/var", "/home"):
                fs, total, used, avail, pct, mnt = parts[0], int(parts[1]), int(parts[2]), int(parts[3]), parts[4], parts[5]
                out.append({"mount": mnt, "fs": fs, "total": total, "used": used, "free": avail, "percent": int(pct.rstrip("%"))})
    except Exception: pass
    return out

def load_uptime():
    la = read("/proc/loadavg").split()[:3]
    up = float(read("/proc/uptime").split()[0] or 0)
    return {"load1": float(la[0]) if la else 0, "load5": float(la[1]) if len(la) > 1 else 0, "load15": float(la[2]) if len(la) > 2 else 0, "uptimeSec": int(up)}

cpu_count = os.cpu_count() or 1
print(json.dumps({
    "cpu": {"count": cpu_count, "percent": cpu_percent()},
    "mem": mem(),
    "disk": disk(),
    "load": load_uptime(),
    "kernel": read("/proc/version").strip()[:200],
}))
PY`;

export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const g = await guard(); if (g) return g;
  const { id } = await ctx.params;
  const r = await exec(id, SCRIPT, { timeoutMs: 10_000 });
  if (!r.ok) return fail(`probe_failed: ${r.stderr || r.stdout}`);
  try {
    const data = JSON.parse(r.stdout);
    return ok({ metrics: data, ranAt: new Date().toISOString() });
  } catch (e) {
    return fail(`parse_failed: ${(e as Error).message}\nraw: ${r.stdout.slice(0, 500)}`);
  }
}
