/*
 * Copyright 2016 - 2025 Gary Talent (gary@drinkingtea.net). All rights reserved.
 */

#pragma once

#include <ox/fs/fs.hpp>
#include <ox/preloader/preloader.hpp>

#include "asset.hpp"
#include "media.hpp"

namespace keel {

struct ManifestEntry {
	static constexpr auto TypeName = "net.drinkingtea.keel.ManifestEntry";
	static constexpr auto TypeVersion = 1;
	uint64_t inode{};
	bool preloaded{};
	ox::String type;
};

OX_MODEL_BEGIN(ManifestEntry)
	OX_MODEL_FIELD(inode)
	OX_MODEL_FIELD(preloaded)
	OX_MODEL_FIELD(type)
OX_MODEL_END()

struct Manifest {
	static constexpr auto TypeName = "net.drinkingtea.keel.Manifest";
	static constexpr auto TypeVersion = 1;
	ox::HashMap<ox::String, ManifestEntry> files;
};

OX_MODEL_BEGIN(Manifest)
	OX_MODEL_FIELD(files)
OX_MODEL_END()


class Context;

struct GbaPlatSpec {
	using PtrType = uint32_t;
	using size_t = uint32_t;

	static constexpr PtrType RomStart = 0x08000000;

	[[nodiscard]]
	static constexpr std::size_t alignOf(bool) noexcept {
		return 1;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(uint8_t) noexcept {
		return 1;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(uint16_t) noexcept {
		return 2;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(uint32_t) noexcept {
		return 4;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(uint64_t) noexcept {
		return 8;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(int8_t)  noexcept {
		return 1;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(int16_t) noexcept {
		return 2;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(int32_t) noexcept {
		return 4;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(int64_t) noexcept {
		return 8;
	}

	[[nodiscard]]
	static constexpr std::size_t alignOf(auto const*) noexcept {
		return 4;
	}

	[[nodiscard]]
	static constexpr auto correctEndianness(auto v) noexcept {
		return ox::toLittleEndian(v);
	}

};

using GbaPreloader = ox::Preloader<GbaPlatSpec>;

namespace detail {
// transformations need to be done after the copy to the new FS is complete
template<typename PlatSpec>
ox::Error preloadObj(
		ox::TypeStore &ts,
		ox::FileSystem &romFs,
		ox::Preloader<PlatSpec> &pl,
		ox::StringView const path) noexcept {
	// load file
	OX_REQUIRE_M(buff, romFs.read(path));
	OX_REQUIRE_M(obj, keel::readAsset(ts, buff));
	if (obj.type()->preloadable) {
		// preload
		auto const size = ox::sizeOf<GbaPlatSpec>(&obj);
		auto const alignment = ox::alignOf<GbaPlatSpec>(obj);
		OX_REQUIRE(a, pl.startAlloc(size, alignment));
		auto const err = ox::preload<GbaPlatSpec, ox::ModelObject>(&pl, &obj);
		OX_RETURN_ERROR(pl.endAlloc());
		OX_RETURN_ERROR(err);
		keel::PreloadPtr const p{.preloadAddr = a};
		OX_RETURN_ERROR(ox::writeMC(p).moveTo(buff));
		auto const &pbufSz = pl.buff().size();
		oxOutf("preloaded {} as a {} @ {} to {} / {}, total size: {}\n",
			path, obj.type()->typeName, a, a + size, pbufSz - 1, pbufSz - a);
	} else {
		// strip the Claw header (it is not needed after preloading) and write back out to dest fs
		OX_RETURN_ERROR(ox::writeMC(obj).moveTo(buff));
	}
	OX_RETURN_ERROR(romFs.write(path, buff.data(), buff.size()));
	return {};
}

// claw file transformations are broken out because path to inode
// transformations need to be done after the copy to the new FS is complete
template<typename PlatSpec>
ox::Error preloadDir(
		Manifest &manifest,
		ox::TypeStore &ts,
		ox::FileSystem &romFs,
		ox::Preloader<PlatSpec> &pl,
		ox::StringViewCR path) noexcept {
	// copy
	oxTracef("pack.preload", "path: {}", path);
	OX_REQUIRE(fileList, romFs.ls(path));
	for (auto const &name : fileList) {
		auto const filePath = ox::sfmt("{}{}", path, name);
		OX_REQUIRE(stat, romFs.stat(filePath));
		if (stat.fileType == ox::FileType::Directory) {
			auto const dir = ox::sfmt("{}{}/", path, name);
			OX_RETURN_ERROR(preloadDir(manifest, ts, romFs, pl, dir));
		} else {
			auto const err = preloadObj(ts, romFs, pl, filePath);
			if (err) {
				oxErrf("\033[31;1;1mCould not preload {}:\n\t{}\n", filePath, toStr(err));
				return err;
			}
			manifest.files[filePath].preloaded = true;
		}
	}
	return {};
}

}

template<typename PlatSpec>
ox::Error appendBinary(ox::Buffer &binBuff, ox::SpanView<char> const &fsBuff, ox::Preloader<PlatSpec> &pl) noexcept {
	constexpr auto padbin = [](ox::BufferWriter &w, unsigned factor) noexcept -> ox::Error {
		return w.write(nullptr, factor - w.buff().size() % factor);
	};
	constexpr ox::StringView mediaHdr   = "KEEL_MEDIA_HEADER_______________";
	constexpr ox::StringView preloadHdr = "KEEL_PRELOAD_HEADER_____________";
	constexpr auto hdrSize = 32u;
	static_assert(mediaHdr.bytes() == hdrSize);
	static_assert(preloadHdr.bytes() == hdrSize);
	ox::BufferWriter w(&binBuff);
	OX_RETURN_ERROR(padbin(w, hdrSize));
	OX_RETURN_ERROR(w.write(mediaHdr.data(), mediaHdr.bytes()));
	OX_RETURN_ERROR(w.write(fsBuff.data(), fsBuff.size()));
	OX_RETURN_ERROR(padbin(w, hdrSize));
	OX_RETURN_ERROR(w.write(preloadHdr.data(), preloadHdr.bytes()));
	OX_RETURN_ERROR(pl.offsetPtrs(binBuff.size()));
	auto const &plBuff = pl.buff();
	OX_RETURN_ERROR(w.write(plBuff.data(), plBuff.size()));
	return {};
}

template<typename PlatSpec>
ox::Error preload(
		Manifest &manifest,
		ox::TypeStore &ts,
		ox::FileSystem &src,
		ox::Preloader<PlatSpec> &pl) noexcept {
	oxOut("Preloading\n");
	return detail::preloadDir(manifest, ts, src, pl, "/");
}

ox::Error pack(Manifest &manifest, keel::Context &ctx, ox::TypeStore &ts, ox::FileSystem &dest) noexcept;

}
