#import <AppKit/AppKit.h>
#include <Ogre.h>
#include <OgreHighLevelGpuProgramManager.h>
#include <array>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <vector>

namespace {
constexpr unsigned size = 64;
const Ogre::String group = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME;

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

// 空格使 Metal 编译器解析 SDK 头，OGRE 资源预处理器只接管连续的 include 指令。
const char* shaders = R"msl(
# include <metal_stdlib>
using namespace metal;
struct Input { float3 position [[attribute(0)]]; };
struct Varying { float4 position [[position]]; float2 uv; };
vertex Varying bookVertex(Input in [[stage_in]]) {
    return {float4(in.position.xy, 0.5, 1), in.position.xy * 0.5 + 0.5};
}
fragment float4 bookSource() {
    return float4(1, 0, 0, 1);
}
fragment float4 bookSample(Varying in [[stage_in]], texture2d<float> source [[texture(0)]],
                           sampler texSampler [[sampler(0)]]) {
    return float4(0, source.sample(texSampler, in.uv).r, 0, 1);
}
)msl";

void createProgram(const Ogre::String& name, const Ogre::String& entry, Ogre::GpuProgramType type) {
    auto program = Ogre::HighLevelGpuProgramManager::getSingleton().createProgram(name, group, "metal", type);
    program->setSource(shaders);
    require(program->setParameter("entry_point", entry), "entry_point parameter unavailable");
    if (type == Ogre::GPT_FRAGMENT_PROGRAM)
        require(program->setParameter("shader_reflection_pair_hint", "BookDepth/MetalVertex"),
                "reflection pair parameter unavailable");
    program->load();
    require(program->isSupported(), "Metal shader unsupported");
}

Ogre::MaterialPtr makeMaterial(const Ogre::String& name, const Ogre::String& fragment) {
    auto material = Ogre::MaterialManager::getSingleton().create(name, group);
    auto* pass = material->getTechnique(0)->getPass(0);
    pass->setLightingEnabled(false);
    pass->setCullingMode(Ogre::CULL_NONE);
    pass->setVertexProgram("BookDepth/MetalVertex");
    pass->setFragmentProgram(fragment);
    return material;
}

Ogre::TexturePtr makeTarget(const Ogre::String& name) {
    return Ogre::TextureManager::getSingleton().createManual(
        name, group, Ogre::TEX_TYPE_2D, size, size, 0, Ogre::PF_BYTE_RGBA, Ogre::TU_RENDERTARGET);
}

Ogre::Entity* setupScene(Ogre::Root& root, Ogre::RenderTarget& target, const Ogre::MeshPtr& mesh,
                         const Ogre::MaterialPtr& material) {
    auto* scene = root.createSceneManager();
    auto* camera = scene->createCamera("Camera");
    camera->setNearClipDistance(0.1f);
    camera->setFarClipDistance(40);
    scene->getRootSceneNode()->createChildSceneNode(Ogre::Vector3(0, 0, 5))->attachObject(camera);
    auto* view = target.addViewport(camera);
    view->setBackgroundColour(Ogre::ColourValue::Black);
    auto* entity = scene->createEntity("Plane", mesh);
    entity->setMaterial(material);
    scene->getRootSceneNode()->createChildSceneNode()->attachObject(entity);
    return entity;
}

std::array<Ogre::uint8, 3> centrePixel(const Ogre::TexturePtr& texture) {
    std::vector<Ogre::uint8> pixels(size * size * 4);
    texture->getBuffer()->blitToMemory(Ogre::PixelBox(size, size, 1, Ogre::PF_BYTE_RGBA, pixels.data()));
    const auto index = ((size / 2) * size + size / 2) * 4;
    return {pixels[index], pixels[index + 1], pixels[index + 2]};
}

void run(const char* plugin) {
    static_assert(OGRE_VERSION == 919043);
    [NSApplication sharedApplication];
    [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
    NSWindow* nativeWindow = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, size, size)
                                                        styleMask:NSWindowStyleMaskBorderless
                                                          backing:NSBackingStoreBuffered
                                                            defer:NO];
    Ogre::Root root("", "", "depth-metal-ogre.log");
    root.loadPlugin(plugin);
    auto* backend = root.getRenderSystemByName("Metal Rendering Subsystem");
    require(backend, "expected Metal Rendering Subsystem");
    root.setRenderSystem(backend);
    root.initialise(false);
    Ogre::NameValuePairList params;
    params["externalWindowHandle"] = std::to_string(reinterpret_cast<std::uintptr_t>((__bridge void*)nativeWindow));
    auto* window = root.createRenderWindow("depth-metal-bootstrap", size, size, false, &params);
    window->setAutoUpdated(false);

    createProgram("BookDepth/MetalVertex", "bookVertex", Ogre::GPT_VERTEX_PROGRAM);
    createProgram("BookDepth/MetalRed", "bookSource", Ogre::GPT_FRAGMENT_PROGRAM);
    createProgram("BookDepth/MetalSample", "bookSample", Ogre::GPT_FRAGMENT_PROGRAM);

    auto plane = Ogre::MeshManager::getSingleton().createPlane(
        "MetalPlane", group, Ogre::Plane(Ogre::Vector3::UNIT_Z, 0), 1.6f, 1.6f);
    auto input = makeTarget("BookDepth/MetalInput");
    auto output = makeTarget("BookDepth/MetalOutput");
    auto inputMaterial = makeMaterial("BookDepth/RedMaterial", "BookDepth/MetalRed");
    auto outputMaterial = makeMaterial("BookDepth/SampleMaterial", "BookDepth/MetalSample");
    outputMaterial->getTechnique(0)->getPass(0)->createTextureUnitState()->setTexture(input);
    auto* inputTarget = input->getBuffer()->getRenderTarget();
    auto* outputTarget = output->getBuffer()->getRenderTarget();
    // 纹理目标按创建顺序登记，手动更新可明确表达写入和采样顺序。
    inputTarget->setAutoUpdated(false);
    outputTarget->setAutoUpdated(false);
    auto* source = setupScene(root, *inputTarget, plane, inputMaterial);
    setupScene(root, *outputTarget, plane, outputMaterial);

    inputTarget->update(false);
    outputTarget->update(false);
    const auto first = centrePixel(input);
    const auto second = centrePixel(output);
    require(first[0] > 240 && first[1] < 10, "input texture must contain red geometry");
    require(second[0] < 10 && second[1] > 240, "output must sample input and write green");
    std::cout << "metal.rtt source=" << unsigned(first[0]) << ',' << unsigned(first[1])
              << " sampled=" << unsigned(second[0]) << ',' << unsigned(second[1]) << '\n';

    source->setVisible(false);
    inputTarget->update(false);
    outputTarget->update(false);
    const auto disabled = centrePixel(output);
    require(disabled[0] < 10 && disabled[1] < 10 && disabled[2] < 10,
            "sampled output must be black with no red source");
    std::cout << "metal.rtt source_disabled=1 output_black=1\n";
}
} // namespace

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "Usage: depth-metal /absolute/path/to/RenderSystem_Metal\n";
        return 2;
    }
    @autoreleasepool {
        try {
            run(argv[1]);
        } catch (const std::exception& error) {
            std::cerr << error.what() << '\n';
            return 1;
        }
    }
}
