# Copyright (c) 2025, Jingrow and Contributors
# See license.txt
import typing
from unittest.mock import MagicMock, Mock, patch

import jingrow
from jingrow.tests.utils import JingrowTestCase

from jcloude.jcloude.pagetype.app.test_app import create_test_app
from jcloude.jcloude.pagetype.bench.test_bench import create_test_bench
from jcloude.jcloude.pagetype.deploy_candidate_build.deploy_candidate_build import DeployCandidateBuild
from jcloude.jcloude.pagetype.release_group.test_release_group import (
	create_test_release_group,
)
from jcloude.jcloude.pagetype.virtual_machine.test_virtual_machine import create_test_virtual_machine

if typing.TYPE_CHECKING:
	from jcloude.infrastructure.pagetype.arm_build_record.arm_build_record import ARMBuildRecord


@patch("jcloude.jcloude.pagetype.bench.bench.jingrow.db.commit", new=MagicMock)
@patch("jcloude.jcloude.pagetype.server.server.jingrow.db.commit", new=MagicMock)
@patch("jcloude.api.bench.jingrow.db.commit", new=MagicMock)
class TestARMBuildRecord(JingrowTestCase):
	def setUp(self):
		super().setUp()

		virtual_machine = create_test_virtual_machine(series="f")
		virtual_machine.create_server()
		self.server = jingrow.get_last_pg("Server")
		app = create_test_app()
		rg = create_test_release_group([app], servers=[self.server.name])
		self.bench = create_test_bench(group=rg, server=self.server.name)
		self.build = jingrow.get_value("Deploy Candidate Build", {})
		jingrow.db.set_value("Deploy Candidate Build", {"name": self.build}, field="status", val="Success")

	@patch.object(DeployCandidateBuild, "pre_build", new=Mock())
	def test_build_trigger(self):
		self.server.collect_arm_images()
		arm_build_record: ARMBuildRecord = jingrow.get_pg(
			"ARM Build Record", jingrow.get_value("ARM Build Record", {})
		)
		deploy_candidate = jingrow.get_value("Deploy Candidate Build", self.build, "deploy_candidate")
		for image in arm_build_record.arm_images:
			# Assert that the arm build is attached and created for the intel build
			self.assertEqual(
				image.build, jingrow.db.get_value("Deploy Candidate", deploy_candidate, "arm_build")
			)

		# Assert no bench update on app server without image pull.
		with self.assertRaises(jingrow.ValidationError):
			arm_build_record.update_image_tags_on_benches()
