#pragma once

#include "VulkanShaderTypes.h"
#include "VulkanVertexFormat.h"
#include "../RhiTypes.h"

#include <cstdint>
#include <string>
#include <vector>

#include <Containers/ArrayView.h>
#include <Containers/String.h>
#include <Containers/StringView.h>

using namespace Death::Containers;

namespace ShaderCompiler
{
	struct ProgramVariant;
}

namespace nCine::RHI::Vulkan
{
	class VulkanBufferObject;
	class VulkanShaderUniforms;
	class VulkanShaderUniformBlocks;

	/**
		@brief Shader program of the Vulkan backend (aliased as `RHI::ShaderProgram`)

		Carries the offline ShaderCompiler reflection (set with @ref SetReflection() like the OpenGL backend)
		from which it imports uniforms, uniform blocks and attributes so the pipeline's uniform machinery runs.
		It also builds the `VkShaderModule` pair from the reflection's embedded `VkVsSpirv`/`VkFsSpirv`, a
		`VkDescriptorSetLayout` from the same reflection (set 0: optional `_Globals` UBO, then the std140 blocks,
		then the combined-image-samplers, in reflection order) and a `VkPipeline` per vertex format. @ref Use()
		records the program as current on the device.
	*/
	class VulkanShaderProgram
	{
		friend class VulkanShaderUniforms;
		friend class VulkanShaderUniformBlocks;

	public:
		enum class Introspection
		{
			Enabled,
			NoUniformsInBlocks,
			Disabled
		};

		enum class Status
		{
			NotLinked,
			CompilationFailed,
			LinkingFailed,
			Linked,
			LinkedWithDeferredQueries,
			LinkedWithIntrospection
		};

		enum class QueryPhase
		{
			Immediate,
			Deferred
		};

		/** @brief Default batch size, indicating the shader is not batched */
		static constexpr std::int32_t DefaultBatchSize = -1;

		VulkanShaderProgram();
		explicit VulkanShaderProgram(QueryPhase queryPhase);
		VulkanShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection, QueryPhase queryPhase);
		VulkanShaderProgram(StringView vertexFile, StringView fragmentFile, Introspection introspection);
		VulkanShaderProgram(StringView vertexFile, StringView fragmentFile);
		~VulkanShaderProgram();

		VulkanShaderProgram(const VulkanShaderProgram&) = delete;
		VulkanShaderProgram& operator=(const VulkanShaderProgram&) = delete;

		/** @brief Returns a backend-neutral identifier uniquely identifying the program (feeds material sort keys; also keys the Vulkan pipeline/descriptor caches) */
		inline std::uint32_t GetUniqueId() const {
			return _handle;
		}
		inline Status GetStatus() const {
			return _status;
		}
		inline Introspection GetIntrospection() const {
			return _introspection;
		}
		inline QueryPhase GetQueryPhase() const {
			return _queryPhase;
		}
		inline std::uint32_t GetBatchSize() const {
			return _batchSize;
		}
		inline void SetBatchSize(std::uint32_t value) {
			_batchSize = value;
		}

		bool IsLinked() const;

		std::uint32_t RetrieveInfoLogLength() const {
			return 0;
		}
		void RetrieveInfoLog(std::string& infoLog) const {
			static_cast<void>(infoLog);
		}

		inline std::uint32_t GetUniformsSize() const {
			return _uniformsSize;
		}
		inline std::uint32_t GetUniformBlocksSize() const {
			return _uniformBlocksSize;
		}

		bool AttachShaderFromFile(ShaderStage stage, StringView filename);
		bool AttachShaderFromString(ShaderStage stage, StringView string);
		bool AttachShaderFromStrings(ShaderStage stage, ArrayView<const StringView> strings);
		bool AttachShaderFromStringsAndFile(ShaderStage stage, ArrayView<const StringView> strings, StringView filename);

		/** @brief Sets the offline reflection consumed by @ref Link() to import uniforms/blocks/attributes */
		inline void SetReflection(const ShaderCompiler::ProgramVariant* reflection) {
			_reflection = reflection;
		}
		/**
			@brief Records the true (program, variant) identity of the loaded shader

			Only the fixed-function console backends consume it (they resolve their generated
			effect tables from this identity instead of the object label); this backend runs
			real shaders and ignores it.
		*/
		inline void SetProgramIdentity(const char* programName, const char* variantName) {
			static_cast<void>(programName);
			static_cast<void>(variantName);
		}


		bool Link(Introspection introspection);
		void Use();
		bool Validate() {
			return true;
		}
		bool FinalizeAfterLinking(Introspection introspection);

		inline std::uint32_t GetAttributeCount() const {
			return std::uint32_t(_attributes.size());
		}
		bool HasAttribute(const char* name) const;
		VulkanVertexFormat::Attribute* GetAttribute(const char* name);

		inline void DefineVertexFormat(const VulkanBufferObject* vbo) {
			DefineVertexFormat(vbo, nullptr, 0);
		}
		inline void DefineVertexFormat(const VulkanBufferObject* vbo, const VulkanBufferObject* ibo) {
			DefineVertexFormat(vbo, ibo, 0);
		}
		void DefineVertexFormat(const VulkanBufferObject* vbo, const VulkanBufferObject* ibo, std::uint32_t vboOffset);

		void Reset();
		void SetObjectLabel(StringView label);

		inline bool GetLogOnErrors() const {
			return _shouldLogOnErrors;
		}
		inline void SetLogOnErrors(bool shouldLogOnErrors) {
			_shouldLogOnErrors = shouldLogOnErrors;
		}

		// -- Backend extensions (used by the uniform caches and the device draw path) --

		/** @brief Publishes a committed loose-uniform value pointer for the device to gather into `_Globals` */
		void SetResolvedUniform(const char* name, const std::uint8_t* data);
		/** @brief Returns the last published value pointer of the named loose uniform, or `nullptr` */
		const std::uint8_t* ResolveUniform(const char* name) const;

		/** @brief Returns `true` if the vertex shader reads vertex attributes (needs vertex input state + a vertex buffer) */
		inline bool HasVertexAttributes() const {
			return !_attributes.empty();
		}
		/** @brief Returns the vertex buffer bound by @ref DefineVertexFormat(), or `nullptr` */
		inline const VulkanBufferObject* GetBoundVbo() const {
			return _boundVbo;
		}
		/** @brief Returns the index buffer bound by @ref DefineVertexFormat(), or `nullptr` */
		inline const VulkanBufferObject* GetBoundIbo() const {
			return _boundIbo;
		}

		// -- SPIR-V modules, descriptor-set layout and the reflection metadata the device uses to
		// build pipelines + descriptor sets. Vulkan handles are opaque integers so this contract header stays
		// free of <vulkan/vulkan.h>; the .cpp reinterprets them. --

		/** @brief One entry of the descriptor set (set 0), matching the offline emitter's binding scheme */
		struct DescriptorBinding
		{
			enum class Kind { Globals, Block, Sampler };
			Kind kind;
			std::uint32_t binding;		// the layout(binding=) number in the SPIR-V
			std::int32_t slot;			// Block: reflection block index (device uniform-range slot); Sampler: texture unit
		};

		/** @brief A loose (default-block) uniform gathered into the "_Globals" UBO, with its std140 placement */
		struct LooseUniform
		{
			String Name;
			std::uint32_t Offset;		// std140 byte offset within _Globals
			std::uint32_t Size;			// byte size of the value
		};

		/** @brief Returns `true` if the SPIR-V modules and layouts were built successfully (draws are skipped otherwise) */
		inline bool HasPipelineState() const {
			return (_vsModule != 0 && _fsModule != 0 && _pipelineLayout != 0);
		}
		/** @brief The vertex-stage `VkShaderModule` (as `std::uint64_t`) */
		inline std::uint64_t GetVsModule() const { return _vsModule; }
		/** @brief The fragment-stage `VkShaderModule` */
		inline std::uint64_t GetFsModule() const { return _fsModule; }
		/** @brief The `VkPipelineLayout` (one descriptor set, set 0) */
		inline std::uint64_t GetPipelineLayout() const { return _pipelineLayout; }
		/** @brief The `VkDescriptorSetLayout` for set 0 */
		inline std::uint64_t GetDescriptorSetLayout() const { return _descriptorSetLayout; }
		/** @brief The descriptor bindings (in reflection order) the device writes each draw */
		inline const std::vector<DescriptorBinding>& GetDescriptorBindings() const { return _descriptorBindings; }
		/** @brief The loose uniforms gathered into "_Globals" (empty if the program has none) */
		inline const std::vector<LooseUniform>& GetLooseUniforms() const { return _looseUniforms; }
		/** @brief std140 byte size of the "_Globals" UBO (0 if the program has no loose uniforms) */
		inline std::uint32_t GetGlobalsSize() const { return _globalsSize; }
		/** @brief The binding number of the "_Globals" UBO (always 0 when present) */
		inline bool HasGlobals() const { return _globalsSize > 0; }

		/** @brief A vertex attribute for building the pipeline's vertex input state */
		struct VertexAttrib
		{
			std::uint32_t Location;
			std::int32_t ComponentCount;
			std::uint32_t Offset;		// byte offset within the vertex
			std::uint32_t Type;			// component type (VertexAttribType numeric value; 0 = float)
			bool Normalized;			// integer components normalized to [0,1] (e.g. u8 colors)
		};
		/**
		 * @brief Fills the current vertex input layout (attributes + per-vertex stride) from the bound vertex format
		 *
		 * Writes at most @p maxAttribs entries into @p outAttribs (a caller-provided array, so the per-draw
		 * pipeline-key computation never touches the heap) and returns the number written.
		 */
		std::uint32_t GetVertexInput(VertexAttrib* outAttribs, std::uint32_t maxAttribs, std::uint32_t& outStride) const;

	private:
		static std::uint32_t _nextHandle;

		std::uint32_t _handle;
		Status _status;
		Introspection _introspection;
		QueryPhase _queryPhase;
		std::uint32_t _batchSize;
		bool _shouldLogOnErrors;
		std::uint32_t _uniformsSize;
		std::uint32_t _uniformBlocksSize;

		std::vector<VulkanUniform> _uniforms;
		std::vector<VulkanUniformBlock> _uniformBlocks;
		std::vector<VulkanAttribute> _attributes;

		const ShaderCompiler::ProgramVariant* _reflection;

		VulkanVertexFormat _vertexFormat;
		const VulkanBufferObject* _boundVbo;
		const VulkanBufferObject* _boundIbo;

		struct ResolvedUniform
		{
			String Name;
			const std::uint8_t* Data;
		};
		std::vector<ResolvedUniform> _resolvedUniforms;

		// GPU objects (opaque integers; see the getters above)
		std::uint64_t _vsModule;
		std::uint64_t _fsModule;
		std::uint64_t _descriptorSetLayout;
		std::uint64_t _pipelineLayout;
		std::vector<DescriptorBinding> _descriptorBindings;
		std::vector<LooseUniform> _looseUniforms;
		std::uint32_t _globalsSize;

		void PerformIntrospection();
		void ImportReflection();
		/** @brief Builds the SPIR-V modules, descriptor-set layout, pipeline layout and reflection metadata (during introspection, while the reflection is still available) */
		void BuildPipelineState();
	};
}
