"""Tests for continuous Jetson GPU activity accounting."""

from __future__ import annotations

import importlib.util
from pathlib import Path


SCRIPT = (
    Path(__file__).parents[2]
    / "services"
    / "monitoring"
    / "scripts"
    / "jetson_tegrastats_exporter.py"
)


def load_module():
    spec = importlib.util.spec_from_file_location("jetson_tegrastats_exporter", SCRIPT)
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_metric_store_retains_gpu_work_between_scrapes():
    module = load_module()
    store = module.MetricStore()

    store.record("GR3D_FREQ 0% GPU@40C RAM 1/2MB", now=10.0)
    store.record("GR3D_FREQ 100% GPU@41C RAM 1/2MB", now=10.25)
    store.record("GR3D_FREQ 0% GPU@40C RAM 1/2MB", now=11.0)
    snapshot = store.snapshot(now=15.0)

    assert snapshot["gr3d_freq_percent"] == 0
    assert snapshot["gr3d_active_seconds_total"] == 0.75
    assert snapshot["tegrastats_samples_total"] == 3
    assert snapshot["last_sample_timestamp_seconds"] == 11.0
    assert snapshot["last_scrape_ts"] == 15.0


def test_activity_metrics_are_exported_as_counters():
    module = load_module()
    body = module.render_metrics(
        {
            "gr3d_freq_percent": 0,
            "gr3d_active_seconds_total": 0.75,
            "tegrastats_samples_total": 3,
        }
    )

    assert "# TYPE jetson_gr3d_freq_percent gauge" in body
    assert "# TYPE jetson_gr3d_active_seconds_total counter" in body
    assert "# TYPE jetson_tegrastats_samples_total counter" in body
