#include <Ogre.h>
#include <OgreMeshSerializer.h>
#include <OgreResourceBackgroundQueue.h>
#include <OgreSubMesh.h>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <future>
#include <iostream>
#include <memory>
#include <set>
#include <stdexcept>
#include <thread>
#include <vector>

namespace {
namespace fs = std::filesystem;
constexpr unsigned size = 96;
const Ogre::String group = "BookDepth";
const Ogre::String meshName = "plane.mesh";
const Ogre::String materialName = "BookDepth/Plane";

void require(bool condition, const char* message) {
    if (!condition)
        throw std::runtime_error(message);
}

class LoadingTrace final : public Ogre::Resource::Listener {
public:
    void loadingComplete(Ogre::Resource*) override {
        require(std::this_thread::get_id() == mainThread, "expected main-thread completion");
        ++loaded;
        std::cout << "resource.load.complete thread=main count=" << loaded << '\n';
    }

    const std::thread::id mainThread = std::this_thread::get_id();
    int loaded = 0;
};

class QueueTrace final : public Ogre::RenderQueue::RenderableListener {
public:
    bool renderableQueued(Ogre::Renderable* renderable, Ogre::uint8 groupId,
                          Ogre::ushort priority, Ogre::Technique** technique,
                          Ogre::RenderQueue*) override {
        require(technique && *technique, "expected a technique");
        require(renderable->getMaterial()->getName() == materialName, "unexpected renderable material");
        Ogre::RenderOperation operation{};
        renderable->getRenderOperation(operation);
        require(operation.useIndexes && operation.indexData, "expected an indexed operation");
        require(operation.indexData->indexCount == 6, "expected six indices");
        visible.insert(renderable);
        std::cout << "queue.candidate group=" << unsigned(groupId) << " priority=" << priority
                  << " scheme=" << (*technique)->getSchemeName()
                  << " passes=" << (*technique)->getNumPasses()
                  << " index_start=" << operation.indexData->indexStart
                  << " index_count=" << operation.indexData->indexCount << '\n';
        return true;
    }

    std::set<Ogre::Renderable*> visible;
};

void writeMaterial(const fs::path& directory) {
    require(fs::create_directory(directory), "fixture directory must be new");
    {
        std::ofstream script(directory / "plane.material");
        script << "material BookDepth/Plane\n{\n  technique\n  {\n    pass\n    {\n"
                  "      lighting off\n      cull_hardware none\n"
                  "    }\n  }\n}\n";
        script.close();
        require(script.good(), "could not write material");
    }
}

void writeMesh(const fs::path& directory) {
    auto& meshes = Ogre::MeshManager::getSingleton();
    auto plane = meshes.createPlane("BookDepthSource", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                                   Ogre::Plane(Ogre::Vector3::UNIT_Z, 0), 1.6f, 1.6f);
    plane->getSubMesh(0)->setMaterialName(materialName, group);
    Ogre::MeshSerializer serializer;
    serializer.exportMesh(plane.get(), (directory / meshName).string(), Ogre::Serializer::ENDIAN_LITTLE);
    serializer.exportMesh(plane.get(), (directory / "plane-big.mesh").string(), Ogre::Serializer::ENDIAN_BIG);
    meshes.remove(plane);

    std::ofstream incomplete(directory / "truncated.mesh", std::ios::binary);
    const char header[] = {0, 0x10, '['};
    incomplete.write(header, sizeof(header));
    incomplete.close();
    require(incomplete.good(), "could not write truncated fixture");
}

void waitForWorker(std::future<void>& future) {
    using namespace std::chrono_literals;
    require(future.wait_for(5s) == std::future_status::ready, "worker timed out");
    future.get();
}

std::size_t colouredPixels(Ogre::RenderWindow& window) {
    std::vector<Ogre::uint8> pixels(size * size * 3);
    const Ogre::PixelBox output(size, size, 1, Ogre::PF_BYTE_RGB, pixels.data());
    window.copyContentsToMemory(Ogre::Box(0, 0, size, size), output, Ogre::RenderTarget::FB_BACK);
    std::size_t coloured = 0;
    for (std::size_t i = 0; i < pixels.size(); i += 3)
        coloured += (pixels[i] | pixels[i + 1] | pixels[i + 2]) != 0;
    return coloured;
}

void checkFactoryPlugin(Ogre::Root& root, Ogre::SceneManager& scene, const char* path) {
    const Ogre::String type = "BookDepthObject";
    require(!root.hasMovableObjectFactory(type), "factory type already registered");
    for (const auto* name : {"BookObjectFirst", "BookObjectSecond"}) {
        root.loadPlugin(path);
        require(root.hasMovableObjectFactory(type), "plugin did not register its factory");
        auto* object = scene.createMovableObject(name, type);
        require(object && object->getMovableType() == type, "plugin object type mismatch");
        scene.destroyMovableObject(object);
        root.unloadPlugin(path);
        require(!root.hasMovableObjectFactory(type), "factory survived library unload");
        std::cout << "plugin.cycle registered=1 created=1 destroyed=1 unregistered=1\n";
    }
}

void run(const char* renderPlugin, const fs::path& assetDirectory, const char* factoryPlugin) {
    static_assert(OGRE_VERSION == 919043);
    static_assert(OGRE_THREAD_SUPPORT == 3, "build OGRE with its default threaded work queue");
    LoadingTrace resourceTrace;
    QueueTrace drawTrace;
    Ogre::Root root("", "", "depth-scene-ogre.log");
    root.loadPlugin(renderPlugin);
    auto* backend = root.getRenderSystemByName("Tiny Rendering Subsystem");
    require(backend, "expected Tiny Rendering Subsystem");
    root.setRenderSystem(backend);
    root.initialise(false);
    auto* window = root.createRenderWindow("depth-book", size, size, false);

    writeMaterial(assetDirectory);
    auto& groups = Ogre::ResourceGroupManager::getSingleton();
    groups.createResourceGroup(group);
    groups.addResourceLocation(assetDirectory.string(), "FileSystem", group);
    groups.initialiseResourceGroup(group);
    auto material = Ogre::MaterialManager::getSingleton().getByName(materialName, group);
    require(material && !material->isLoaded(), "script should register an unloaded material");
    std::cout << "group.initialised material=" << material->getName() << " loaded=0\n";
    writeMesh(assetDirectory);
    // Refresh the FileSystem location so the new mesh is in the group index.
    groups.removeResourceLocation(assetDirectory.string(), group);
    groups.addResourceLocation(assetDirectory.string(), "FileSystem", group);

    auto& meshes = Ogre::MeshManager::getSingleton();
    auto& background = Ogre::ResourceBackgroundQueue::getSingleton();
    auto [resource, created] = meshes.createOrRetrieve(meshName, group);
    require(created, "expected a new disk-backed resource");
    auto mesh = std::static_pointer_cast<Ogre::Mesh>(resource);
    mesh->addListener(&resourceTrace);

    auto workerThread = std::make_shared<std::promise<std::thread::id>>();
    auto thread = workerThread->get_future();
    root.getWorkQueue()->addTask([workerThread] { workerThread->set_value(std::this_thread::get_id()); });
    using namespace std::chrono_literals;
    require(thread.wait_for(5s) == std::future_status::ready, "work queue did not run");
    require(thread.get() != resourceTrace.mainThread, "expected a worker thread");
    auto pending = background.load(mesh);
    waitForWorker(pending);
    require(mesh->isPrepared() && !mesh->isLoaded() && resourceTrace.loaded == 0,
            "future should be ready before the main-thread load");
    std::cout << "resource.future.ready prepared=1 loaded=0 completions=0\n";

    root.getWorkQueue()->processMainThreadTasks();
    require(mesh->isLoaded() && mesh->getNumSubMeshes() == 1 && resourceTrace.loaded == 1,
            "expected a decoded mesh and one notification");
    require(mesh->getSubMesh(0)->getMaterialName() == materialName, "wrong decoded material");
    std::cout << "mesh.decoded submeshes=" << mesh->getNumSubMeshes() << '\n';

    auto bigEndian = meshes.load("plane-big.mesh", group);
    require(bigEndian->getNumSubMeshes() == 1 &&
                bigEndian->getSubMesh(0)->indexData->indexCount == 6,
            "big endian geometry differs");
    meshes.remove(bigEndian);
    std::cout << "mesh.big_endian submeshes=1 indices=6\n";

    auto [truncated, wasTruncatedCreated] = meshes.createOrRetrieve("truncated.mesh", group);
    require(wasTruncatedCreated, "expected a new truncated resource");
    bool truncatedRejected = false;
    try {
        truncated->load();
    } catch (const Ogre::Exception&) {
        truncatedRejected = true;
    }
    require(truncatedRejected && !truncated->isLoaded(), "truncated header should fail decoding");
    meshes.remove(truncated);
    std::cout << "mesh.truncated rejected=1 loaded=0\n";

    auto [missing, wasCreated] = meshes.createOrRetrieve("missing.mesh", group);
    require(wasCreated, "expected a new missing resource");
    auto failed = background.load(missing);
    bool missingRejected = false;
    try {
        waitForWorker(failed);
    } catch (const Ogre::FileNotFoundException&) {
        missingRejected = true;
    }
    require(missingRejected && !missing->isPrepared() && !missing->isLoaded(),
            "missing file should leave the resource unloaded");
    meshes.remove(missing);
    std::cout << "resource.missing rejected=1 loaded=0\n";

    auto* scene = root.createSceneManager();
    if (factoryPlugin)
        checkFactoryPlugin(root, *scene, factoryPlugin);
    scene->getRenderQueue()->setRenderableListener(&drawTrace);
    auto* camera = scene->createCamera("Camera");
    camera->setNearClipDistance(0.1f);
    camera->setFarClipDistance(40);
    auto* cameraNode = scene->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(0, 0, 5));
    cameraNode->attachObject(camera);
    auto* view = window->addViewport(camera);
    view->setBackgroundColour(Ogre::ColourValue::Black);

    auto* leftNode = scene->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(-1, 0, 0));
    auto* rightNode = scene->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(1, 0, 0));
    auto* left = scene->createEntity("Left", mesh);
    auto* right = scene->createEntity("Right", mesh);
    leftNode->attachObject(left);
    rightNode->attachObject(right);
    require(left->getMesh().get() == right->getMesh().get(), "expected shared mesh storage");
    require(leftNode->getPosition() != rightNode->getPosition(), "expected independent transforms");

    require(root.renderOneFrame(), "visible frame failed");
    auto pixels = colouredPixels(*window);
    require(drawTrace.visible.size() == 2 && pixels > 0 && window->getStatistics().triangleCount == 4,
            "expected two visible entities and four rendered triangles");
    std::cout << "frame.visible candidates=2 triangles=4 nonblack_pixels=" << pixels << '\n';

    drawTrace.visible.clear();
    cameraNode->setPosition(20, 0, 5);
    require(root.renderOneFrame(), "culled frame failed");
    require(drawTrace.visible.empty() && colouredPixels(*window) == 0 &&
            window->getStatistics().triangleCount == 0, "expected both entities culled");
    std::cout << "frame.culled candidates=0 triangles=0 nonblack_pixels=0\n";

    scene->getRenderQueue()->setRenderableListener(nullptr);
    scene->destroyEntity(left);
    scene->destroyEntity(right);
    mesh->unload();
    require(!mesh->isLoaded(), "expected an unloaded mesh");
    mesh->load();
    require(mesh->isLoaded() && mesh->getNumSubMeshes() == 1, "expected disk reload");
    std::cout << "mesh.reload submeshes=1\n";

    mesh->unload();
    const auto completions = resourceTrace.loaded;
    auto beforeExit = background.load(mesh);
    waitForWorker(beforeExit);
    require(mesh->isPrepared() && !mesh->isLoaded(), "expected pending main-thread work");
    root.getWorkQueue()->processMainThreadTasks();
    require(resourceTrace.loaded == completions + 1 && mesh->isLoaded(),
            "expected resource completion before shutdown");
    mesh->removeListener(&resourceTrace);
    mesh->unload();
    std::cout << "resource.drained_before_shutdown loaded=0\n";

    auto marker = std::make_shared<bool>(false);
    root.getWorkQueue()->addMainThreadTask([marker] { *marker = true; });
    root.shutdown();
    require(!*marker, "shutdown should not pump this pending marker");
    std::cout << "root.shutdown pending_main_thread_marker_dispatched=0\n";
}
} // namespace

int main(int argc, char** argv) {
    if (argc != 3 && argc != 4) {
        std::cerr << "Usage: depth-scene /absolute/path/to/RenderSystem_Tiny new-assets-directory [factory-plugin]\n";
        return 2;
    }
    try {
        run(argv[1], fs::absolute(argv[2]), argc == 4 ? argv[3] : nullptr);
    } catch (const std::exception& error) {
        std::cerr << error.what() << '\n';
        return 1;
    }
}
