# Copyright (c) 2025, JINGROW
# For license information, please see license.txt

from __future__ import annotations

import json
import typing

import jingrow
import requests
from jingrow.model.document import Page

if typing.TYPE_CHECKING:
	from jcloude.jcloude.pagetype.server.server import Server


class ProcessSnapshot(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		bench: DF.Link
		dump: DF.JSON | None
		server: DF.Link
	# end: auto-generated types

	def check_bench_on_server(self):
		if not jingrow.get_value("Bench", {"name": self.bench, "server": self.server}):
			jingrow.throw(f"{self.bench} does not exist on server {self.server}")

	def validate(self):
		self.check_bench_on_server()

	def after_insert(self):
		server: Server = jingrow.get_pg("Server", self.server)
		try:
			self.dump = json.dumps(server.agent.get_snapshot(self.bench), indent=2)
		except requests.exceptions.HTTPError as e:
			self.dump = json.dumps({"error": str(e)}, indent=2)
		self.save()
