#!/usr/bin/python3

from __future__ import annotations

import json
import os
import signal
import subprocess
import time
from pathlib import Path
from typing import Any

POWERCAP = Path("/sys/class/powercap")
POWER_SUPPLY = Path("/sys/class/power_supply")
PCI_DEVICES = Path("/sys/bus/pci/devices")
RUNTIME_DIRECTORY = Path(os.environ.get("RUNTIME_DIRECTORY", "/run/blob-energy"))
STATE_DIRECTORY = Path(os.environ.get("STATE_DIRECTORY", "/var/lib/blob-energy"))
NOW_FILE = RUNTIME_DIRECTORY / "now.json"
HOURS_FILE = STATE_DIRECTORY / "hours.json"
MINUTES_FILE = STATE_DIRECTORY / "minutes.json"
SAMPLE_SECONDS = 10
MINUTES_KEPT = 48 * 60
HOURS_KEPT = 3 * 366 * 24
BUCKET_FIELDS = ("cpuWh", "gpuWh", "sensorWh", "acSeconds", "batteryWh", "batterySeconds")


class RaplCounter:
  def __init__(self, directory: Path) -> None:
    self.energy_file = directory / "energy_uj"
    try:
      self.wrap = int((directory / "max_energy_range_uj").read_text())
    except (OSError, ValueError):
      self.wrap = 0
    self.last = self.read()

  def read(self) -> int | None:
    try:
      return int(self.energy_file.read_text())
    except (OSError, ValueError):
      return None

  def watts(self, seconds: float) -> float | None:
    current = self.read()
    previous, self.last = self.last, current
    if current is None or previous is None or seconds <= 0:
      return None
    delta = current - previous
    if delta < 0:
      delta += self.wrap
    return max(0.0, delta / 1_000_000 / seconds)


def rapl_counters() -> dict[str, RaplCounter]:
  counters: dict[str, RaplCounter] = {}
  for directory in sorted(POWERCAP.glob("intel-rapl:*")):
    try:
      name = (directory / "name").read_text().strip()
    except OSError:
      continue
    key = {"package-0": "package", "core": "core", "uncore": "uncore", "psys": "platform"}.get(name)
    if key and key not in counters:
      counters[key] = RaplCounter(directory)
  return counters


def nvidia_watts() -> float | None:
  for device in PCI_DEVICES.glob("*"):
    try:
      if (device / "vendor").read_text().strip() != "0x10de" or not (device / "class").read_text().startswith("0x03"):
        continue
      if (device / "power" / "runtime_status").read_text().strip() != "active":
        return 0.0
    except OSError:
      continue
    try:
      output = subprocess.run(
        ["nvidia-smi", "--query-gpu=power.draw", "--format=csv,noheader,nounits"],
        capture_output=True, text=True, timeout=5,
      ).stdout
      return float(output.strip().splitlines()[0])
    except (OSError, subprocess.TimeoutExpired, ValueError, IndexError):
      return None
  return None


def battery_watts() -> float | None:
  for battery in POWER_SUPPLY.glob("BAT*"):
    try:
      if (battery / "status").read_text().strip() != "Discharging":
        return None
      power_file = battery / "power_now"
      if power_file.exists():
        return int(power_file.read_text()) / 1_000_000
      current = int((battery / "current_now").read_text())
      voltage = int((battery / "voltage_now").read_text())
      return current * voltage / 1_000_000_000_000
    except (OSError, ValueError):
      continue
  return None


def read_json(path: Path, fallback: Any) -> Any:
  try:
    return json.loads(path.read_text(encoding="utf-8"))
  except (OSError, ValueError):
    return fallback


def write_json(path: Path, data: Any) -> None:
  temporary = path.with_suffix(".tmp")
  temporary.write_text(json.dumps(data, separators=(",", ":")), encoding="utf-8")
  os.chmod(temporary, 0o644)
  temporary.replace(path)


class Meter:
  def __init__(self) -> None:
    self.counters = rapl_counters()
    self.hours: dict[str, list[float]] = read_json(HOURS_FILE, {})
    self.minutes: list[list[float]] = read_json(MINUTES_FILE, [])
    self.minute_sum = [0.0] * len(BUCKET_FIELDS)
    self.minute_start = int(time.time() // 60 * 60)
    self.boot_wh = [0.0] * len(BUCKET_FIELDS)
    self.last_time = time.monotonic()
    self.running = True

  def sample(self) -> dict[str, Any]:
    now = time.monotonic()
    seconds, self.last_time = now - self.last_time, now
    readings = {key: counter.watts(seconds) for key, counter in self.counters.items()}
    dgpu = nvidia_watts()
    battery = battery_watts()
    package = readings.get("package")
    platform = readings.get("platform")
    cpu = readings.get("core") if readings.get("core") is not None else package
    gpu = (readings.get("uncore") or 0.0) + (dgpu or 0.0)
    sensor = max(value for value in (platform, package, 0.0) if value is not None) + (dgpu or 0.0)
    return {
      "time": int(time.time()),
      "seconds": round(seconds, 2),
      "cpu": round(cpu or 0.0, 2),
      "gpu": round(gpu, 2),
      "sensor": round(sensor, 2),
      "package": round(package or 0.0, 2),
      "platform": round(platform or 0.0, 2) if platform is not None else None,
      "dgpu": round(dgpu, 2) if dgpu is not None else None,
      "battery": round(battery, 2) if battery is not None else None,
      "onBattery": battery is not None,
      "sensors": sorted(key for key, value in readings.items() if value is not None) + (["nvidia"] if dgpu is not None else []),
    }

  def bucket_values(self, reading: dict[str, Any]) -> list[float]:
    hours = reading["seconds"] / 3600
    on_battery = reading["onBattery"]
    return [
      reading["cpu"] * hours,
      reading["gpu"] * hours,
      0.0 if on_battery else reading["sensor"] * hours,
      0.0 if on_battery else reading["seconds"],
      reading["battery"] * hours if on_battery else 0.0,
      reading["seconds"] if on_battery else 0.0,
    ]

  def record(self, reading: dict[str, Any]) -> None:
    values = self.bucket_values(reading)
    hour_key = str(int(reading["time"] // 3600 * 3600))
    bucket = self.hours.setdefault(hour_key, [0.0] * len(BUCKET_FIELDS))
    for index, value in enumerate(values):
      bucket[index] += value
      self.minute_sum[index] += value
      self.boot_wh[index] += value
    minute_start = int(reading["time"] // 60 * 60)
    if minute_start != self.minute_start:
      self.minutes.append([self.minute_start] + [round(value, 5) for value in self.minute_sum])
      self.minutes = self.minutes[-MINUTES_KEPT:]
      self.minute_sum = [0.0] * len(BUCKET_FIELDS)
      self.minute_start = minute_start
      self.flush()

  def flush(self) -> None:
    if len(self.hours) > HOURS_KEPT:
      for key in sorted(self.hours, key=int)[:-HOURS_KEPT]:
        del self.hours[key]
    write_json(HOURS_FILE, {key: [round(value, 5) for value in bucket] for key, bucket in self.hours.items()})
    write_json(MINUTES_FILE, self.minutes)

  def publish(self, reading: dict[str, Any]) -> None:
    write_json(NOW_FILE, dict(reading, interval=SAMPLE_SECONDS, sinceBoot=[round(value, 5) for value in self.boot_wh], fields=list(BUCKET_FIELDS)))

  def stop(self, *_: object) -> None:
    self.running = False

  def run(self) -> None:
    signal.signal(signal.SIGTERM, self.stop)
    signal.signal(signal.SIGINT, self.stop)
    while self.running:
      time.sleep(SAMPLE_SECONDS)
      if not self.running:
        break
      reading = self.sample()
      self.record(reading)
      self.publish(reading)
    self.flush()


if __name__ == "__main__":
  RUNTIME_DIRECTORY.mkdir(parents=True, exist_ok=True)
  STATE_DIRECTORY.mkdir(parents=True, exist_ok=True)
  Meter().run()
